1
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?

Ravali
  • 23
  • 3
  • Check the comments on Jon Skeet's answer to [this question](https://stackoverflow.com/questions/1065168/does-disposing-streamreader-close-the-stream). – John Wu Jun 13 '19 at 04:40

1 Answers1

2

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.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86