两者在功能上有什么区别StreamWriter.Flush()
and StreamWriter.Close()
?
当我的数据没有正确写入文件时,我添加了两个Flush()
and Close()
到我的代码的末尾。然而,我意识到添加either Flush()
or Close()
允许数据被正确写入。
当我阅读 MSDN 文档时,我无法准确理解这些方法的作用;我只是发现其中之一对于确保数据正确写入是必要的。任何进一步的解释将不胜感激。
Where s
是要写入的字符串,这是我的代码当前的样子:
StreamWriter sw = File.CreateText("TextOutput.txt");
sw.Write(s);
sw.Flush();
sw.Close();
根据答案的反馈,我重写了我的代码using
块,它实现IDisposable
并在对象被释放时自动将流写入文件:
using (StreamWriter sw = File.CreateText("TextOutput.txt"))
{
sw.Write(s);
}
StreamWriter.Flush()
可以在需要清除缓冲区时随时调用,并且流将保持打开状态。
StreamWriter.Close()
用于关闭流,此时缓冲区也被刷新。
但您实际上不需要调用其中任何一个。任何时候我看到一个.Close()
在代码中,我将其视为代码味道,因为它通常意味着意外异常可能导致资源保持打开状态。你什么should做的就是创造你的StreamWriter
using 块中的变量,如下所示:
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)