c# – 在StreamWriter和StreamReader上完成

前端之家收集整理的这篇文章主要介绍了c# – 在StreamWriter和StreamReader上完成前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我有这个: @H_301_2@StreamWriter cout = new StreamWriter("test.txt"); cout.WriteLine("XXX"); // here IOException... StreamReader cin = new StreamReader("test.txt"); string text = cin.ReadLine();

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

事实上,如果我这样做:

@H_301_2@StreamWriter cout = new StreamWriter("test.txt"); cout.WriteLine("XXX"); cout.Close(); StreamReader cin = new StreamReader("test.txt"); string text = cin.ReadLine();

我也不例外.

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

@H_301_2@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以及类似类的最佳方法是使用:

@H_301_2@using (StreamWriter cout = new StreamWriter("test.txt")) { cout.WriteLine("XXX"); } using (StreamReader cin = new StreamReader("test.txt")) { string text = cin.ReadLine(); }

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

猜你在找的C#相关文章