如何使用 StreamWriter 强制写入文件? [英] How do I force write to file using StreamWriter?

查看:42
本文介绍了如何使用 StreamWriter 强制写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是使用 streamwriter writer = new StreamWriter(file) 写入文件.问题是在 writer.close() 之前它实际上不会写入文件.

I always use streamwriter writer = new StreamWriter(file) to write to file. The problem is it wont actually write to file until writer.close().

如果在 class create 和 class close 之间发生了不好的事情(并且程序永远不会到达 writer close),我将不会在文件中获得任何信息.如何在创建和关闭之间强制写入?

If between class create and class close something bad happens (and the program never reaches writer close), I wont get any information in the file. How to force write between create and close?

推荐答案

确保您的代码包含在 using 语句中:

Make sure you have your code wrapped in a using statement:

using (var writer = new StreamWriter(file))
{
    // do your writing
}

这将通过为您处理(并刷新和关闭)流来帮助清理",例如在要抛出未处理的异常时不会调用 Close() 的情况在流实例化之后.以上基本等价于:

This will help "clean up" by disposing (and flushing and closing) the stream for you, such as in situations where Close() would not get called if an unhandled exception were to be thrown after instantiation of the stream. The above is basically equivalent to:

{
    var writer = new StreamWriter(file);
    try
    {
        // do your writing
    }
    finally
    {
        if (writer != null)
            ((IDisposable)writer).Dispose();
    }
}

注意:任何实现 IDisposable 接口的东西都应该在 using 块中使用,以确保它被正确处理.

Note: anything that implements the IDisposable interface should be used within a using block to make sure that it is properly disposed.

这篇关于如何使用 StreamWriter 强制写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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