What is the difference in functionality between StreamWriter.Flush()
and StreamWriter.Close()
?
When my data wasn't being written correctly to a file, I added both Flush()
and Close()
to the end of my code. However, I realized that adding either Flush()
or Close()
allowed the data to be written correctly.
I wasn't able to pick up on exactly what each of these methods does when I read the MSDN docs; I only figured out that one or the other is necessary to ensure data is written correctly. Any further explanation would be much appreciated.
Where s
is a string to be written, here's what my code looks like currently:
StreamWriter sw = File.CreateText("TextOutput.txt");
sw.Write(s);
sw.Flush();
sw.Close();
Based on feedback from the answers, I've rewritten my code in a using
block, which implements IDisposable
and will automatically take care of writing the stream to the file when the object is disposed:
using (StreamWriter sw = File.CreateText("TextOutput.txt"))
{
sw.Write(s);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…