Ravali
Ravali

Reputation: 23

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();
        }
    }
}

If FileStream fs is assigned to null code is running without warnings but I don't want to assign filestream to null i.e., fs=null in using Statement.

So, what is the correct way of writing it without assigning null value?

Upvotes: 1

Views: 42

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

Get rid of the 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 is already doing something like this:

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

And disposing will, by it's very nature, close the stream.

See this question for more info about using.

Upvotes: 2

Related Questions