【发布时间】:2023-01-02 16:42:38
【问题描述】:
我有一个将消息写入文本文件的功能。但是当传递带有“Environment.NewLine”的字符串时,它不会将新行写入文本文件。相反,它会写入“\r\n”。 如何纠正这个?我尝试过使用“\n”而不是“Environment.NewLine”。新线路仍然没有到来。 只有在将带有换行符的字符串传递给函数时才会发生此问题。像变量“消息”
string message= "First "+Environment.NewLine+" message.";
LogTheDetails(message);
public static void LogTheDetails(String message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
string FilePath = path + "/" + currentdate + ".txt";
if (!File.Exists(FilePath)) //FILE WRITING FIRST TIME
{
File.Create(FilePath).Dispose();
using (TextWriter tw = new StreamWriter(FilePath))
{
tw.WriteLine("============================================================\n --Logs--");
}
}
else if (File.Exists(FilePath))//IF FILE ALREADY EXIST - APPEND LINES
{
string testString= "testString"+ Environment.NewLine+ "WithNewLine";
File.AppendAllText(FilePath, "\n============================================================\n");
File.AppendAllText(FilePath, message);
File.AppendAllText(FilePath, testString);
File.AppendAllText(FilePath, "\n============================================================\n");
}
}
输出
============================================================
--Logs--
============================================================
First \r\n message.
testString
WithNewLine
============================================================
预期输出:
============================================================
--Logs--
============================================================
First
message.
testString
WithNewLine
============================================================
【问题讨论】:
-
你的问题不清楚。在什么情况下你想写
\n?哪一行应该为它写一个新行?我也看不到你写的任何一行First -
@viveknuna string message= "第一条"+Environment.NewLine+"消息。";
-
您在哪里以及如何调用该函数? - 的:代码很难阅读,因为你的格式太乱了!
-
每当 Environment.NewLine 出现时,它应该换行。现在输出显示为 '/r/n'
-
@TaW 请现在检查我的代码
标签: c# string file utf-8 system.io.file