2017-10-21 161 views
0

在doc.microsoft網站,我們有這樣C#打開文本文件

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

StreamReader的解決辦法,而我也遇到不同的例子是這樣

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

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

它有什麼優勢定義爲空的的FileStream?

+0

不是你正在比較的蘋果和橘子嗎? – rene

+3

StreamReader在引擎蓋下仍然有一個Stream(在這種情況下是一個FileStream)。它採用Stream(二進制數據)並將其作爲Unicode文本呈現。只要看看兩個類的方法,並決定哪一個對您的預期用法最有用。 –

+0

@rene不知道,這就是我問的原因。 –

回答

3

在第一個例子中,是StreamReader的不可用try塊的外側(和將成爲Dispose() d反正)。

在第二個示例中,FileStream 可用於try塊之外,但可能爲空(發生異常時)。這取決於你以後處理它。