进程无法访问文件“目录\文件”因为它正在被 C# 文件写入器中的另一个进程使用

发布于 2024-09-30 13:43:44 字数 783 浏览 8 评论 0原文

当我尝试保存现有文件时,我收到此错误:

该进程无法访问该文件,因为该文件正在被另一个进程使用

当文件不存在时它可以工作,但是当我尝试再次写入该文件时,会出现错误。我当时没有访问或使用该文件。

这是代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

森林散布 2024-10-07 13:43:44

您的程序可能没有正确处理文件流,从而使文件保持打开状态。

使用 using 语句确保正确处置:

using(StreamWriter writer = new StreamWriter(file,true))
{
    writer.WriteLine(username + "," + barcode + "," + DateTime.Now.ToString("yyyy-MM-dd HH.mm")+ "," + remarks);
    writer.Close();
}

Your program is probably not disposing of the file stream properly, keeping the file open.

Use the using statement to ensure proper disposal:

using(StreamWriter writer = new StreamWriter(file,true))
{
    writer.WriteLine(username + "," + barcode + "," + DateTime.Now.ToString("yyyy-MM-dd HH.mm")+ "," + remarks);
    writer.Close();
}
旧时浪漫 2024-10-07 13:43:44

或者您可以在关闭后使 writer 对象无效。

Or you can nullify the writer object after closing.

就像说晚安 2024-10-07 13:43:44

尝试在 writer.Close(); 之前使用 writer.Flush();

try to use writer.Flush(); before writer.Close();

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文