【问题标题】:CA2202 Do not dispose objects multiple times, How to Solve?CA2202 不要多次处理对象,如何解决?
【发布时间】:2019-06-13 04:19:37
【问题描述】:
private string GetFileContent(string path)
{
    if(File.Exists(HttpContext.Current.Server.MapPath(path)))
    {
        FileStream fs=null;
        try
        {
            fs = new FileStream(HttpContext.Current.Server.MapPath(path), FileMode.Open, FileAccess.Read);
            using (TextReader tr = new StreamReader(fs))
            {
                fs.Flush();
                return tr.ReadToEnd();
            }
        }
        finally
        {
             fs.Close();
        }
    }
}

如果将 FileStream fs 分配给 null 代码运行时没有警告,但我不想将 filestream 分配给 null,即在 using 语句中 fs=null。

那么,不赋值空值的正确写法是什么?

【问题讨论】:

标签: c# static-code-analysis


【解决方案1】:

摆脱try/finally:

    using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(path), FileMode.Open, FileAccess.Read))
    using (TextReader tr = new StreamReader(fs))
    {
        fs.Flush();
        return tr.ReadToEnd();
    }

using 已经在做这样的事情了:

{
    FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(path), FileMode.Open, FileAccess.Read);
    try
    {
        // code inside the `using` goes here
    }
    finally
    {
        fs.Dispose();
    }
}

从本质上讲,处理将关闭流。

有关using 的更多信息,请参阅this question

【讨论】:

    猜你喜欢
    • 2014-04-10
    • 2019-04-29
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    相关资源
    最近更新 更多