using 语句 FileStream 和/或 StreamReader - Visual Studio 2012 警告 [英] using statement FileStream and / or StreamReader - Visual Studio 2012 Warnings

查看:25
本文介绍了using 语句 FileStream 和/或 StreamReader - Visual Studio 2012 警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的 Visual Studio 2012 抱怨我一直使用的常见代码组合.我知道这似乎有点矫枉过正,但我​​在我的代码中做了以下只是为了确定".

The new Visual Studio 2012 is complaining about a common code combination I have always used. I know it seems like overkill but I have done the following in my code 'just to be sure'.

using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using (var sr = new StreamReader(fs))
    {
        // Code here
    }
}

Visual Studio 正在警告"我我不止一次处理 fs.所以我的问题是,写这个的正确方法是:

Visual studio is 'warning' me that I am disposing of fs more than once. So my question is this, would the proper way to write this be:

using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    var sr = new StreamReader(fs);
    // do stuff here
}

或者我应该这样做(或其他一些未提及的变体).

Or should I do it this way (or some other variant not mentioned).

var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

using (var sr = new StreamReader(fs))
{
    // Code here
}

我在 StackOverflow 中搜索了几个问题,但没有找到直接解决此组合最佳实践的问题.

I searched several questions in StackOverflow but did not find something that addressed the best practice for this combination directly.

谢谢!

推荐答案

以下是微软推荐的 这样做.它又长又笨重,但安全:

The following is how Microsoft recommends doing it. It is long and bulky, but safe:

FileStream fs = null;
try
{
    fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    using (TextReader tr= new StreamReader(fs))
    {
        fs = null;
        // Code here
    }
}
finally
{
    if (fs != null)
        fs.Dispose();
}

这个方法将始终确保所有的东西都被处理掉,不管可能抛出什么异常.例如,如果 StreamReader 构造函数抛出异常,FileStream 仍会被正确处理.

This method will always ensure that everything is disposed that should be despite what exceptions may be thrown. For example, if the StreamReader constructor throws an exception, the FileStream would still be properly disposed.

这篇关于using 语句 FileStream 和/或 StreamReader - Visual Studio 2012 警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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