san*_*art 1 c# file overwrite save
我在c#,windows窗体中编辑.我希望在同一个文件中保存文件的"新内容"(通常使用'save'选项),但是我收到IOException,[进程无法访问文件'filename',因为它正由另一个进程使用.我有写入新文件的方法,它的工作原理.如何使用它来覆盖当前文件.
编辑:我正在使用二进制文件http://msdn.microsoft.com/en-us/library/atxb4f07.aspx
有可能是当你加载文件时,你没有关闭FileStream或用于阅读它的任何东西.始终为您的流(以及其他类型的实现)使用using语句IDisposable,这应该不是问题.(当然如果你真的在一个单独的应用程序中打开该文件,那完全是另一个问题.)
所以代替:
// Bad code
StreamReader reader = File.OpenText("foo.txt");
string data = reader.ReadToEnd();
// Nothing is closing the reader here! It'll keep an open
// file handle until it happens to be finalized
Run Code Online (Sandbox Code Playgroud)
你应该使用更像:
string data;
using (TextReader reader = File.OpenText("foo.txt"))
{
data = reader.ReadToEnd();
}
// Use data here - the handle will have been closed for you
Run Code Online (Sandbox Code Playgroud)
或者理想情况下,使用File为您执行所有操作的方法:
string text = File.ReadAllText("foo.txt");
Run Code Online (Sandbox Code Playgroud)