加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在StreamWriter和StreamReader上完成

发布时间:2020-12-15 08:27:56 所属栏目:百科 来源:网络整理
导读:如果我有这个: 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");

// 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块结束时,这也会确定性地关闭文件.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读