【发布时间】:2014-09-13 19:53:15
【问题描述】:
我在 MSDN 文档中看到了以下示例代码,演示了如何使用 System.IO.StreamReader 类从 System.IO.FileStream 对象中读取 UTF-8 文本。两个嵌套的using 语句让我觉得是多余的——肯定在其中一个对象上调用Dispose() 可以解决问题,并正确释放文件句柄? (来源:http://msdn.microsoft.com/en-us/library/yhfzs7at.aspx)
using (FileStream fs = new FileStream(path, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
}
用以下方式重写该代码不是更简单,也同样正确吗?
using (FileStream fs = new FileStream(path, FileMode.Open))
{
StreamReader sr = new StreamReader(fs);
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
【问题讨论】:
-
我相信处置所有实现
IDisposable的东西是个好主意。 -
类似问题的好答案:stackoverflow.com/q/9949377/361684
标签: c# filestream dispose streamreader using