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

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

问题描述

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

在我的数据没有被正确地写入文件,我说无论同花顺()关闭()来我的code结束。但是,我意识到,加入的或者同花顺()关闭()允许的数据要正确写入。

我无法拿起正是这些方法的确,当我读MSDN文档;我只是想通了,一方或另一方是必要的,以保证数据的正确写入。任何进一步的解释会更AP preciated。


其中,取值将被写入字符串,这里就是我的code看起来像当前:

  StreamWriter的SW = File.CreateText(TextOutput.txt);
        sw.Write(多个);
        sw.Flush();
        sw.Close();
 


基于来自答案反馈

,我已经重写我的code在使用块,它实现的IDisposable 并将自动采取写入流以当对象被布置在文件的护理:

 使用(StreamWriter的SW = File.CreateText(TextOutput.txt))
        {
            sw.Write(多个);
        }
 

解决方案

StreamWriter.Flush()可以叫你需要清除缓冲区内的任何时间,流将继续开放。

StreamWriter.Close()是关闭流,此时缓冲区也刷新。

但是,你真的不应该需要调用这些。任何时候,我看到一个 .Close()在code我把它看作一个code嗅觉,因为这通常意味着一个意外的异常可能会导致资源悬空。你的应该采取什么的做的,是用块创建的StreamWriter 变量,像这样的:

 使用(VAR作家=新的StreamWriter(somefilepath.txt))
{
   //写一堆东西在这里
} //该StreamWriter的将被关闭,在这里刷新,即使抛出异常。
 

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

解决方案

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.

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

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