[英]The process cannot access the file because error while trying to write to a file
I am getting this error when i am trying to write to a file in this manner: 当我尝试以这种方式写入文件时,我收到此错误:
try
{
if (!File.Exists(path))
File.CreateText(file.ToString());
sw = flag == 1 ? File.CreateText(file.ToString()) : File.AppendText(file.ToString()); //Exception here
sw.WriteLine(textToWrite);
status = true;
}
But before to this file i made a delete attempt to it also in another function in this way: 但在此文件之前,我以这种方式在另一个函数中进行了删除尝试:
try
{
File.Delete(path);
status = true;
}
Exception: {"The process cannot access the file ... because it is being used by another process."}
例外: {"The process cannot access the file ... because it is being used by another process."}
Now as it seems file is still either taken by delete process of by the File.CreateText
function, how can i make them release the file so i can start writing to it? 现在看来文件仍然是由File.CreateText
函数的删除过程,我如何让它们释放文件,以便我可以开始写它?
File.CreateText will return a streamwriter which has a file stream still opened . File.CreateText将返回一个仍然打开文件流的streamwriter。 You should be using that. 你应该使用它。 That is the reason why you get exception in successive calls to open the file. 这就是为什么在连续调用打开文件时会出现异常的原因。
Try this. 尝试这个。
using(var sw = File.CreateText(...))
{
//Do whatever
}
If you want to delete the file before writing a new file, try this: 如果要在写入新文件之前删除该文件,请尝试以下操作:
File.WriteAllText(path, textToWrite);
If you want to append to a file (or create), try this: 如果要附加到文件(或创建),请尝试以下操作:
File.AppendAllText(path, textToWrite);
Both of these methods close the file after writing. 这两种方法都在写入后关闭文件。
CreateText returns StremWriter which you miss it. CreateText返回你错过的StremWriter。 That's why it remains opened. 这就是为什么它仍然开放。 You can easily close it: 你可以轻松关闭它:
StreamReader sr = File.OpenText(path);
sr.WriteLine(textToWrite);
sr.Close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.