【问题标题】:No line breaks when using File.WriteAllText(string,string)使用 File.WriteAllText(string,string) 时没有换行符
【发布时间】:2015-12-24 17:34:21
【问题描述】:

我注意到我使用下面的代码创建的文件中没有换行符。在我也存储文本的数据库中,这些都存在。

string story = "Critical error occurred after " 
  + elapsed.ToString("hh:mm:ss") 
  + "\n\n" + exception.Message;
File.WriteAllText(path, story);

所以在short googling 之后,我了解到我应该使用 Environment-NewLine 而不是文字 \n 来引用新行。所以我添加了如下所示。

string story = "Critical error occurred after " 
  + elapsed.ToString("hh:mm:ss") 
  + "\n\n" + exception.Message;
  .Replace("\n", Environment.NewLine);
File.WriteAllText(path, story);

仍然,输出文件中没有换行符。我错过了什么?

【问题讨论】:

    标签: c# file line-breaks


    【解决方案1】:

    试试 StringBuilder 方法 - 它更具可读性,您无需记住 Environment.NewLine\n\r\n

    var sb = new StringBuilder();
    
    string story = sb.Append("Critical error occurred after ")
                   .Append(elapsed.ToString("hh:mm:ss"))
                   .AppendLine()
                   .AppendLine()
                   .Append(exception.Message)
                   .ToString();
    File.WriteAllText(path, story);
    

    简单的解决方案:

    string story = "Critical error occurred after " 
      + elapsed.ToString("hh:mm:ss") 
      + Environment.NewLine + exception.Message;
    File.WriteAllLines(path, story.Split('\n'));
    

    【讨论】:

    • 没有解决原来的问题,虽然建议本身很好。我发布了一个非常简单的示例,跳过了构建器,以缩短内容。关键是使用 File 类而不是任何其他用于写入的类,并且仍然得到换行符。这可能吗?
    • @KonradViltersten 更新了答案,只需将 \n 替换为 Environment.NewLine 就可以了
    • 呵呵,你看到我的第二个例子了吗?多余的行,倒数第二行?我正在添加 Environment.NewLine 但它 still 没有进入文件。因此问题。但我会给你一个免费赠品,因为我发现了问题所在。而不是 WriteAllText,我需要去 WriteAllLinesSplit 故事。
    【解决方案2】:

    您可以使用如下代码的 WriteLine() 方法

       using (StreamWriter sw = StreamWriter(path)) 
            {
                string story = "Critical error occurred after "  +elapsed.ToString("hh:mm:ss");
                sw.WriteLine(story);   
                sw.WriteLine(exception.Message); 
            }
    

    【讨论】:

    • 文件中没有这种方法。当然,我可以换到另一个班级,但我希望保持简短。我很好奇 File 类中没有换行符......
    【解决方案3】:

    而不是使用

    File.WriteAllText(path, content);
    

    使用

    File.WriteAllLines(path, content.Split('\n'));
    

    【讨论】:

      【解决方案4】:

      WriteAllText 去除换行符,因为它不是文本。

      【讨论】:

      • 这实际上是不正确的。你试过了吗?它接受给定编码中的所有字符。这包括在 Windows 中换行所需的两个字符。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 2016-08-27
      • 2018-01-08
      相关资源
      最近更新 更多