Jacob Alley Jacob Alley - 1 month ago 13
C# Question

ConsoleOutput formatting vs TextFile formatting

I have a string builder that i am generating and when i display it in the console, it is formatted perfectly:

enter image description here

but when i attempt to export the stringbuilder.ToString() to a text file, the formatting gets lost in translation:

enter image description here

foreach (var item in companyList.Keys)
{
reportForText.AppendLine(item.ToString());

foreach (var user in companyList[item])
{


reportForText.Append(String.Format("\n{0,-22}: ", user.Name));
foreach (var group in user.GroupList)
{
reportForText.Append(String.Format("{0}\n", group).PadRight(25 + group.Length));
}
}
}
reportForText.AppendLine();
reportForText.AppendLine();
}

Answer

Notepad.exe does not support \n as a newline, it only supports (as far as I know) \r\n as a newline. You can fix this by using Environment.NewLine instead of \n for a new line (or even using \r\n directly): "A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms". These days it's not a "Windows or Unix or Mac" thing because as you see it's dependent on the program itself and what characters it has defined to represent "new lines", so IMO this is a question about Notepad.exe and how it works and it should be irrelevant if you are on Unix or non-Unix, despite the language support for Environment.NewLine. This is corroborated by the Windows Console itself supporting \n as a newline even though it's a "non-Unix" platform.

An unrelated issue you might run into is the font being used. Both Notepad.exe and Console by default use fixed-width fonts, so all your spacing currently lines up. But if you change to a variable width font then your colons and stuff will stop lining up perfectly.

Comments