2017-10-21 163 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块之外,但可能为空(发生异常时)。这取决于你以后处理它。