Writing to txt file with StreamWriter and FileStream
c#
Solution
It sounds like you did not flush the stream.
http://msdn.microsoft.com/en-us/library/system.io.stream.flush.aspx
It looks like StreamWriter writes to a buffer before writing to the final destination, in this case, the file. You may also be able to set the AutoFlush property and not have to explicitly flush it.
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.autoflush.aspx
To answer your question, when you use the "using" block, it calls dispose on the StreamWriter, which must in turn call Flush.
Problem
I ran into something interesting when using a `StreamWriter` with a `FileStream` to append text to an existing file in .NET 4.5 (haven't tried any older frameworks). I tried two ways, one worked and one didn't. I'm wondering what the difference between the two is. Both methods contained the following code at the top ``` if (!File.Exists(filepath)) using (File.Create(filepath)); ``` I have the creation in a `using` statement because I've found through personal experience that it's the best way to ensure that the application fully closes the file. Non-Working Method: ``` using (FileStream f = new FileStream(filepath, FileMode.Append,FileAccess.Write)) (new StreamWriter(f)).WriteLine("somestring"); ``` With this method nothing ends up being appended to the file. Working Method: ``` using (FileStream f = new FileStream(filepath, FileMode.Append,FileAccess.Write)) using (StreamWriter s = new StreamWriter(f)) s.WriteLine("somestring"); ``` I've done a bit of Googling, without quite knowing what to search for, and haven't found anything informative. So, why is it that the anonymous `StreamWriter` fails where the (non-anonymous? named?) `StreamWriter` works?