我知道这可能看起来很愚蠢,但为什么只有在我关闭 () 文件时以下代码才有效?如果我不关闭文件,则不会写入整个流。
步骤:
- 在表单加载时运行此代码。
- 显示后使用鼠标关闭表单。
- 程序终止。
当文件对象超出范围时,它不应该被刷新或自动关闭吗?我是 C# 的新手,但我习惯于在 C++ 析构函数中添加对 Close() 的调用。
// Notes: complete output is about 87KB. Without Close(), it's missing about 2KB at the end.
// Convert to png and then convert that into a base64 encoded string.
string b64img = ImageToBase64(img, ImageFormat.Png);
// Save the base64 image to a text file for more testing and external validation.
StreamWriter outfile = new StreamWriter("../../file.txt");
outfile.Write(b64img);
// If we don't close the file, windows will not write it all to disk. No idea why
// that would be.
outfile.Close();
最佳答案
C# 没有自动确定性清理。如果你想控制它何时运行,你必须确保调用清理函数。 using
block 是执行此操作的最常见方式。
如果您不自己进行清理调用,那么当垃圾收集器决定内存需要用于其他用途时,清理就会发生,这可能会在很长一段时间后发生。
using (StreamWriter outfile = new StreamWriter("../../file.txt")) {
outfile.Write(b64img);
} // everything is ok, the using block calls Dispose which closes the file
编辑:正如 Harvey 指出的那样,虽然在收集对象时将尝试清理,但这并不能保证成功。为避免循环引用问题,运行时不会尝试以“正确”顺序终结对象,因此 FileStream
实际上可能在 StreamWriter
终结器时已经失效运行并尝试刷新缓冲输出。
如果您处理需要清理的对象,请使用 using
(对于局部范围的使用)或通过调用 IDisposable.Dispose
(对于长时间生活对象,例如类(class)成员的指称)。
关于c# - 为什么我必须在 C# 中关闭 () 一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3944666/