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

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

问题描述

新的Visual Studio 2012在抱怨一个共同code组合我一直使用。我知道这似乎有点小题大做,但我做了以下在我的code'只是为了确保。

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 (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using (TextReader tr = 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 (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    TextReader tr = new StreamReader(fs);
    // do stuff here
}

或者我应该做这种方式(或没有提到其他一些变量)。

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

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

using (TextReader tr = new StreamReader(fs))
{
    // Code here
}

我在搜索计算器的几个问题,但没有找到的东西,解决的最佳实践的这种组合直接。

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天全站免登陆