简体   繁体   中英

Error: The process cannot access the file '…' because it is being used by another process

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?

Here a part of the code:

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

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.

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.

只是在这里没有看到转储文件的代码,但是如果你正在使用FileStreamsBitmap对象,我会仔细检查以确保在运行第二种方法之前正确处理所有这些对象。

The only clear solution on this case is keep track of who is handling access to the directory and fix the bug, by releasing that access.

If the object/resource that handling access is 3rd party, or by any means is not possible to change or access, it's a time to revise an architecture, to handle IO access in a different way.

Hope this helps.

Sounds like you are not releasing the file handle when the file is created. Try doing all of your IO within the using statement, that way the file will be released automatically when you are finished with it.

http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.80%29.aspx

  • I have seen cases where a virus scanner will scan the new file and prevent the file from being deleted, though that is highly unlikely.

  • Be sure to .Dispose of all IDisposable objects and make sure that nothing has changed your Environment.CurrentDirectory to the directory you want to delete.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM