CA2202 对象不能多次dispose,如何解决?

CA2202 Do not dispose objects multiple times, How to Solve?

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 分配给空代码 运行 没有警告,但我不想将文件流分配给空,即在使用语句时 fs=null。

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

去掉 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