簡體   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