我正在尝试将String Builder保存到文件中,但它不会创建新行.输出应该是这样的

class Program
{
static public void justify(List<string> words, int width)
{
//some code to build the arrays
int ii = 0, jj;
StringBuilder builder = new StringBuilder();
do
{
jj = result[ii];
for(int k = ii; k < jj; k++)
{
builder.Append(words[k] + " ");
}
builder.Append("\n");
ii = jj;
}
while(jj < words.Count);
Console.WriteLine(builder.ToString());
StreamWriter file = new StreamWriter("output.txt");
file.Write(builder.ToString());
file.Close();
}
static void Main(string[] args)
{
string file_extention, file1;
file1 = Console.ReadLine();
file_extention = "C:\\Users\\sayed\\Desktop\\" + file1 + ".txt";
string text = System.IO.File.ReadAllText(@file_extention);
result = text.Split(' ').ToList();
justify(result, 10);
}
}
Run Code Online (Sandbox Code Playgroud)
那是因为您应该\r\n在Windows中使用新行.\n是Unix.你应该用
builder.AppendLine();
Run Code Online (Sandbox Code Playgroud)
这会自动执行此操作.更确切地说,在Unix平台上AppendLine()附加\r\n非Unix平台和字符串\n.
请注意,您的文件确实包含\n一些编辑器甚至在Windows上解释为换行符的文件.例如,记事本不会.