简体   繁体   English

C# 打开文本文件

[英]C# open text file

On doc.microsoft site,we have streamreader solution like this在 doc.microsoft 站点上,我们有这样的流阅读器解决方案

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?定义可为空的 FileStream 有什么好处吗?

In the first example, the StreamReader is not available outside of the try block (and will be Dispose() d of anyway).在第一个示例中, StreamReader 在try块之外不可Dispose()无论如何都是Dispose() d)。

In the second example, the FileStream is available outside of the try block, but may be null (when an exception happened).在第二个例子,因此FileStream可用外try块,但也可以是空(异常时发生过)。 It is up to you to Dispose of it later.稍后由您来处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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