CA2202 Не выбрасывайте объекты несколько раз, как решить? - PullRequest
1 голос
/ 13 июня 2019
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 при использовании Statement.

Итак, что является правильнымспособ записи без присвоения нулевого значения?

1 Ответ

2 голосов
/ 13 июня 2019

Избавьтесь от 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.

...