Aidan Quinn
Aidan Quinn

Reputation: 1188

StreamWriter() isn't working as it should?

Ive got an array of properties from an object that I want append to a textfile.

Here is my code:

StreamWriter Writer = new StreamWriter("Cars.txt");

for (int i = 0; i < 4; i++)
  {
     Writer.Write(CarProps[i]); 
  }

I added stuff to the textfile manually, but when I run the program, the text file comes up blank.

Upvotes: 0

Views: 86

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460340

Use the using statement to flush the writer:

using(var writer = new StreamWriter("Cars.txt"))
{
    for (int i = 0; i < 4; i++)
    {
        writer.Write(CarProps[i]); 
    }
}

If you don't set StreamWriter.AutoFlush to true, it won't write to the stream immediately. Therefore you have to call Flush or Close manually. Flush is called on Dispose which is invoked by the using.

Upvotes: 3

Related Questions