[英]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.