Do I need to explicitly close the StreamReader in C# when using it to load a file into a string variable?

后端 未结 6 644
予麋鹿
予麋鹿 2020-12-05 12:53

Example:

variable = new StreamReader( file ).ReadToEnd();

Is that acceptable?

相关标签:
6条回答
  • 2020-12-05 13:30

    It's good practice to close StreamReader. Use the following template:

    string contents;
    
    using (StreamReader sr = new StreamReader(file)) 
    {
       contents = sr.ReadToEnd();
    }
    
    0 讨论(0)
  • 2020-12-05 13:35

    Yes, whenever you create a disposable object you must dispose of it preferably with a using statement

    using (var reader = new StreamReader(file)) {
      variable = reader.ReadToEnd(file);
    }
    

    In this case though you can just use the File.ReadAllText method to simplify the expression

    variable = File.ReadAllText(file);
    
    0 讨论(0)
  • 2020-12-05 13:38

    You're better off using the using keyword; then you don't need to explicitly close anything.

    0 讨论(0)
  • 2020-12-05 13:42

    You need to Dispose of objects that implement IDisposable. Use a using statement to make sure it gets disposed without explicitly calling the Dispose method.

    using (var reader = new StreamReader(file))
    {
      variable = reader.ReadToEnd();
    }
    

    Alternately, use File.ReadAllText(String)

    variable = File.ReadAllText(file);
    
    0 讨论(0)
  • 2020-12-05 13:50

    No, this will not close the StreamReader. You need to close it. Using does this for you (and disposes it so it's GC'd sooner):

    using (StreamReader r = new StreamReader("file.txt"))
    {
      allFileText = r.ReadToEnd();
    }
    

    Or alternatively in .Net 2 you can use the new File. static members, then you don't need to close anything:

    variable = File.ReadAllText("file.txt");
    
    0 讨论(0)
  • 2020-12-05 13:50

    You should always dispose of your resources.

    // the using statement automatically disposes the streamreader because
    // it implements the IDisposable interface
    using( var reader = new StreamReader(file) )
    {
        variable = reader.ReadToEnd();
    }
    

    Or at least calling it manually:

    reader = new StreamReader(file);
    variable = reader.ReadToEnd();
    reader.Close();
    
    0 讨论(0)
提交回复
热议问题