Search code examples
c#streamwriter

How to write to an existing txt file c#


I have created some code which creates a txt file with an initial text, however when I try to call the method again with a new msg it does not add it to the txt file. Below is my code:

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);
   }
}

If I try and call the method a second time the new msg does not get added. Any help will be appreciated.


Solution

  • You should not use File.CreateText, but this StreamWriter overload instead:

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

    See MSDN