Search code examples
c#.netstreamwriter

How to rewrite a file or append to a file using StreamWriter


I am using this code:

for ($number=0; $number < 5; $number++) {
    StreamWriter x = new StreamWriter("C:\\test.txt");
                 x.WriteLine(number);
                 x.Close();
}

If something is in test.txt, this code will not overwrite it. I have two questions:

  1. How can I make it overwrite the file?
  2. How can I append to the same file?

Solution

  • Try the FileMode enumerator:

    // will append to end of file
    FileStream fappend = File.Open("C:\\test.txt", FileMode.Append); 
    
    // will create the file or overwrite it if it already exists
    FileStream fcreate = File.Open("C:\\test.txt", FileMode.Create);