What is the difference in functionality between StreamWriter.Flush() and StreamWriter.Close() ?
When my data was not written to the file correctly, I added both ends of Flush() and Close() to the end of my code. However, I realized that adding either Flush() or Close() allowed me to write the data correctly.
I was not able to understand what each of these methods does when I read MSDN documents; I just found out that one or the other is necessary to ensure that the data is written correctly. Any further explanation would be greatly appreciated.
Where s is the line to be written, here is what my code currently looks like:
StreamWriter sw = File.CreateText("TextOutput.txt"); sw.Write(s); sw.Flush(); sw.Close();
Based on the feedback from the responses, I rewrote my code in the using block, which implements IDisposable and will automatically take care of writing the stream to the file when placing the object:
using (StreamWriter sw = File.CreateText("TextOutput.txt")) { sw.Write(s); }
Ben McCormack Mar 10 '10 at 15:13 2010-03-10 15:13
source share