【问题标题】:How to write to an existing txt file c# [duplicate]如何写入现有的文本文件c# [重复]
【发布时间】:2018-04-27 18:34:32
【问题描述】:

我创建了一些代码来创建一个带有初始文本的 txt 文件,但是当我尝试使用新的 msg 再次调用该方法时,它不会将其添加到 txt 文件中。以下是我的代码:

string example = "test";
WriteToLgo(example);

public static void WriteToLog(String inputtext)
{
   string location= @"C:\Users\";
   string NameOfFile = "test.txt";
   string fileName= String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now, NameOfFile);
   string path= Path.Combine(location, fileName);
   using (StreamWriter sr= File.CreateText(path))
   {
      sr.WriteLine(inputtext);
   }
}

如果我再次尝试调用该方法,则不会添加新的 msg。任何帮助将不胜感激。

【问题讨论】:

    标签: c# streamwriter


    【解决方案1】:

    您不应该使用File.CreateText,而是使用此StreamWriter 重载:

    //using append = true
    using (StreamWriter sr = new StreamWriter(path, true))
    {
        sr.WriteLine(inputtext);
    }
    

    MSDN

    【讨论】:

    • 谨慎使用这种方法,因为在以这种方式打开文件以进行追加之前,您需要检查以确保文件存在。如果文件不存在,它将异常。您可以改用 File.AppendText(path) ,它将追加或创建。
    • @BretLipscomb:这不是医生所说的:Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.
    • 嗯,是的。你是对的。猜猜他们在某个时候改变了这一点,或者我正在考虑不同的实现。谢谢。
    • @BretLipscomb:我知道那种感觉 ;-)
    【解决方案2】:

    File.CreateText 每次只创建一个新文件,覆盖其中的任何内容。不附加到现有文件。

    您应该使用 File.AppendText(...) 打开现有文件以附加内容,或使用基本 StreamWriter 类通过附加选项打开它

    类似:

    using (StreamWriter sr = File.AppendText(path))
    {
      sr.WriteLine(inputtext);
    }
    

    如果您使用基本 StreamWriter 类而不是 File.AppendText,您可以像 StreamWriter sr = new StreamWriter(path, true); 一样使用它但是,您必须在打开文件进行追加之前检查文件是否存在。可能会在您的情况下推荐 File.AppendText。

    【讨论】:

    • 你为什么怀疑它??
    • 没错,new 应该被删除。监督它是我的错。 @Bret 应该删除它。
    • 刚刚更新,大家说的都对。在这种情况下不需要“新”。我的监督。这就是我不使用智能感知的结果。
    猜你喜欢
    • 1970-01-01
    • 2014-01-18
    • 2016-04-14
    • 1970-01-01
    • 2013-06-14
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多