StreamWriter.Flush() 和 StreamWriter.Close() 有什么区别? [英] What is the difference between StreamWriter.Flush() and StreamWriter.Close()?

查看:49
本文介绍了StreamWriter.Flush() 和 StreamWriter.Close() 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

StreamWriter.Flush()StreamWriter.Close() 在功能上有什么区别?

What is the difference in functionality between StreamWriter.Flush() and StreamWriter.Close()?

当我的数据没有正确写入文件时,我将 Flush()Close() 添加到我的代码末尾.但是,我意识到添加要么 Flush()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.

当我阅读 MSDN 文档时,我无法准确了解每种方法的作用;我只发现其中一个是确保数据正确写入所必需的.任何进一步的解释将不胜感激.

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.

其中 s 是要写入的字符串,这是我的代码目前的样子:

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();

<小时>

根据答案的反馈,我在 using 块中重写了我的代码,该块实现了 IDisposable 并将自动处理将流写入文件当对象被释放时:


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);
}

推荐答案

StreamWriter.Flush() 可以在您需要清除缓冲区的任何时候调用,并且流将保持打开状态.

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

StreamWriter.Close() 用于关闭流,此时缓冲区也被刷新.

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

但是您真的不需要调用其中任何一个.每当我在代码中看到 .Close() 时,我都会将其视为代码异味,因为这通常意味着意外异常可能导致资源保持打开状态.您应该做的是在 using 块中创建您的 StreamWriter 变量,如下所示:

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.

这篇关于StreamWriter.Flush() 和 StreamWriter.Close() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆