我有一些代码,当它执行时,它抛出一个IOException,说
进程无法访问文件'filename',因为它正在被 另一个进程
这意味着什么?我能做些什么?
我有一些代码,当它执行时,它抛出一个IOException,说
进程无法访问文件'filename',因为它正在被 另一个进程
这意味着什么?我能做些什么?
当前回答
我下面的代码解决这个问题,但我建议 首先,你需要了解是什么导致了这个问题,并尝试通过修改代码来找到解决方案
我可以给出另一种方法来解决这个问题,但更好的解决方案是检查你的编码结构,并尝试分析是什么导致这种情况发生,如果你没有找到任何解决方案,那么你可以使用下面的代码
try{
Start:
///Put your file access code here
}catch (Exception ex)
{
//by anyway you need to handle this error with below code
if (ex.Message.StartsWith("The process cannot access the file"))
{
//Wait for 5 seconds to free that file and then start execution again
Thread.Sleep(5000);
goto Start;
}
}
其他回答
使用FileShare修复了我打开文件的问题,即使它被另一个进程打开。
using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
}
在上传图像时出现问题,无法删除并找到解决方案。gl高频
//C# .NET
var image = Image.FromFile(filePath);
image.Dispose(); // this removes all resources
//later...
File.Delete(filePath); //now works
我得到这个错误是因为我在执行File。移动到没有文件名的文件路径时,需要在目标中指定完整路径。
我下面的代码解决这个问题,但我建议 首先,你需要了解是什么导致了这个问题,并尝试通过修改代码来找到解决方案
我可以给出另一种方法来解决这个问题,但更好的解决方案是检查你的编码结构,并尝试分析是什么导致这种情况发生,如果你没有找到任何解决方案,那么你可以使用下面的代码
try{
Start:
///Put your file access code here
}catch (Exception ex)
{
//by anyway you need to handle this error with below code
if (ex.Message.StartsWith("The process cannot access the file"))
{
//Wait for 5 seconds to free that file and then start execution again
Thread.Sleep(5000);
goto Start;
}
}
我有下面的场景会导致同样的错误:
上传文件到服务器 然后在旧文件上传后删除它们
大多数文件都很小,但也有少数文件很大,因此试图删除这些文件会导致无法访问文件的错误。
然而,要找到这个问题并不容易,解决方法很简单,就是“等待任务完成执行”:
using (var wc = new WebClient())
{
var tskResult = wc.UploadFileTaskAsync(_address, _fileName);
tskResult.Wait();
}