错误:该进程无法访问文件“ ...”,因为它正在被另一个进程使用 [英] Error: The process cannot access the file '...' because it is being used by another process

查看:77
本文介绍了错误:该进程无法访问文件“ ...”,因为它正在被另一个进程使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个始终创建目录并将一些文件(图像)放入其中的功能。
首次运行代码时,没有问题。第二次(总是),当我必须删除目录时它会出错(因为我想重新创建它以将图像放入其中)。错误是该进程无法访问文件'...,因为它正在被另一个进程使用。访问此文件的唯一过程是此功能。
就像函数不离开文件一样。

I have a function that always creates a directory and put in it some files (images). When the code runs first time, no problem. Second time (always), it gets an error when I have to delete the directory (because I want to recreate it to put in it the images). The error is "The process cannot access the file '...' because it is being used by another process". The only process that access to this files is this function. It's like the function "doesn't leave" the files.

如何用清晰的解决方案解决这个问题?

How can I resolve this with a clear solution?

下面是代码的一部分:

String strPath = Environment.CurrentDirectory.ToString() + "\\sessionPDF";
if (Directory.Exists(strPath))
      Directory.Delete(strPath, true); //Here I get the error
Directory.CreateDirectory(strPath);
//Then I put the files in the directory


推荐答案

如果您的代码或其他进程正在提供图像,则它们将被无限期锁定。如果是IIS,则在提供服务时会被锁定一小段时间。我不确定,但是如果资源管理器正在为图片创建缩略图,它可能会在锁定图片的同时将其锁定。可能需要花一秒钟的时间,但是如果您的代码和该过程发生冲突,则是竞争条件。

If your code or another process is serving up the images, they will be locked for an indefinite amount of time. If it's IIS, they're locked for a short time while being served. I'm not sure about this, but if Explorer is creating thumbs for the images, it may lock the files while it does that. It may be for a split second, but if your code and that process collide, it's a race condition.

请确保在完成操作后释放锁。如果该类实现了IDisposable,则在您不对该对象进行大量工作的情况下,在其周围包装using语句:

Be sure you release your locks when you're done. If the class implements IDisposable, wrap a using statement around it if you're not doing extensive work on that object:

using (var Bitmap = ... || var Stream = ... || var File = ...) { ... }

...之后将关闭对象,并且文件不会被锁定。

...which will close the object afterwards and the file will not be locked.

这篇关于错误:该进程无法访问文件“ ...”,因为它正在被另一个进程使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆