Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
778 views
in Technique[技术] by (71.8m points)

c# - What is the difference between StreamWriter.Flush() and StreamWriter.Close()?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

StreamWriter.Flush() can be called any time you need to clear the buffer, and the stream will remain open.

StreamWriter.Close() is for closing the stream, at which point the buffer is also flushed.

But you shouldn't really need to call either of these. Any time I see a .Close() in code I take that as a code smell, because it usually means an unexpected exception could cause the resource to be left open. What you should do, is create your StreamWriter variable in a using block, like this:

using (var writer = new StreamWriter("somefilepath.txt"))
{
   // write a bunch of stuff here
} // the streamwriter WILL be closed and flushed here, even if an exception is thrown.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...