I have a function to write a message to text file. But when passing a string with 'Environment.NewLine', it is not writes a new line to the text file. Instead it writes '\r\n'. How to correct this? I have tried with '\n' instead of 'Environment.NewLine'. Still the new line is not coming. The issue is happens only when passing a string with new line to the function. Like variable 'message'
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");
}
}
Output
============================================================
--Logs--
============================================================
First \r\n message.
testString
WithNewLine
============================================================
Expected Output:
============================================================
--Logs--
============================================================
First
message.
testString
WithNewLine
============================================================
Below piece of code gave the output you are looking for, I tried it in .net 5 console application.