微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 在StreamWriter和StreamReader上完成

如果我有这个:
StreamWriter cout = new StreamWriter("test.txt");
cout.WriteLine("XXX");

// here IOException...
StreamReader cin = new StreamReader("test.txt");
string text = cin.ReadLine();

clr抛出IOException,因为我还没有关闭cout.

事实上,如果我这样做:

StreamWriter cout = new StreamWriter("test.txt");
cout.WriteLine("XXX");

cout.Close();

StreamReader cin = new StreamReader("test.txt");
string text = cin.ReadLine();

我也不例外.

但是如果我这样做然后退出应用程序:

StreamReader cin = new StreamReader("test.txt");
string text = cin.ReadLine();

没有关闭cin文件可以从OS打开和写入.

但是,阅读StreamReader.cs的源代码,我没有找到析构函数方法(即~StreamReader(…)).那么如果垃圾收集器没有调用dispose并且没有终结方法,谁会释放该文件

解决方法

StreamReader和StreamWriter使用FileStream来访问该文件. FileStream使用 SafeFileHandle来存储底层OS文件句柄.由于SafeFileHandle类控制非托管资源,因此它正确地具有关闭文件句柄的终结器(您称之为析构函数).

But If I do this and then exit from the application: […] without closing cin the file can from the OS opened and written

当进程终止时,该进程使用的所有资源都将释放到操作系统.如果您的应用程序忘记关闭文件句柄并不重要(即使SafeFileHandle不会“忘记”).无论您的应用程序编写得多么糟糕,您都将始终观察所描述的行为.

我只想指出使用StreamReader和StreamWriter以及类似类的最佳方法是使用:

using (StreamWriter cout = new StreamWriter("test.txt")) {
  cout.WriteLine("XXX");
}

using (StreamReader cin = new StreamReader("test.txt")) {
  string text = cin.ReadLine();
}

即使在处理文件时抛出异常,当using块结束时,这也会确定性地关闭文件.

原文地址:https://www.jb51.cc/csharp/243669.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐