进程无法访问文件“目录\文件”因为它正在被 C# 文件写入器中的另一个进程使用
当我尝试保存现有文件时,我收到此错误:
该进程无法访问该文件,因为该文件正在被另一个进程使用
当文件不存在时它可以工作,但是当我尝试再次写入该文件时,会出现错误。我当时没有访问或使用该文件。
这是代码:
string directory = filepath + "Updates\\" + dir;
if(!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
remarks = remarks.Trim();
remarks = remarks.Replace("\r\n","<br>");
remarks = remarks.Replace(",","|");
string file = directory + "\\" + getIndex(barcode) + ".asdt";
StreamWriter writer = new StreamWriter(file,true);
writer.WriteLine(username + "," + barcode + "," + DateTime.Now.ToString("yyyy-MM-dd HH.mm")+ "," + remarks);
writer.Close();
当我检查它时,线路上出现错误:
StreamWriter writer = new StreamWriter(file,true);
这可能是什么原因?
I receive this error when ever I attempt to save on the existing file:
the process can not access the file because it is being used by another process
It works when a file doesn't exist, but when I attempt to write in it again the error shows up. I'm not accessing or using the file that time.
here is the code:
string directory = filepath + "Updates\\" + dir;
if(!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
remarks = remarks.Trim();
remarks = remarks.Replace("\r\n","<br>");
remarks = remarks.Replace(",","|");
string file = directory + "\\" + getIndex(barcode) + ".asdt";
StreamWriter writer = new StreamWriter(file,true);
writer.WriteLine(username + "," + barcode + "," + DateTime.Now.ToString("yyyy-MM-dd HH.mm")+ "," + remarks);
writer.Close();
When I checked it the error occurs on the line:
StreamWriter writer = new StreamWriter(file,true);
what could be the cause of this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的程序可能没有正确处理文件流,从而使文件保持打开状态。
使用
using
语句确保正确处置:Your program is probably not disposing of the file stream properly, keeping the file open.
Use the
using
statement to ensure proper disposal:或者您可以在关闭后使 writer 对象无效。
Or you can nullify the writer object after closing.
尝试在
writer.Close();
之前使用writer.Flush();
try to use
writer.Flush();
beforewriter.Close();