简体   繁体   中英

C# open text file

On doc.microsoft site,we have streamreader solution like this

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {   // Open the text file using a stream reader.
            using (StreamReader sr = new StreamReader("TestFile.txt"))
            {
            // Read the stream to a string, and write the string to the console.
                String line = sr.ReadToEnd();
                Console.WriteLine(line);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

But I have also come across different examples like this

FileStream fin = null;
try {
  fin = new FileStream("test", FileMode.Open);
}

catch(IOException exc) {
  Console.WriteLine(exc.Message);
}

Is there any advantage in defining nullable FileStream?

In the first example, the StreamReader is not available outside of the try block (and will be Dispose() d of anyway).

In the second example, the FileStream is available outside of the try block, but may be null (when an exception happened). It is up to you to Dispose of it later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM