繁体   English   中英

C# 打开文本文件

[英]C# open text file

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

但我也遇到过这样的不同例子

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

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

定义可为空的 FileStream 有什么好处吗?

在第一个示例中, StreamReader 在try块之外不可Dispose()无论如何都是Dispose() d)。

在第二个例子,因此FileStream可用外try块,但也可以是空(异常时发生过)。 稍后由您来处理它。

暂无
暂无

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

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