Cannot delete files from a directory

家住魔仙堡 提交于 2020-01-06 04:21:45

问题


I am describing my work process bellow:

  1. I get image files from a directory.

  2. Creating a PictureBox array for displaying the images.

  3. Creating a Image array from the files that I got from the directory. I am creating this array for making the image source of PictureBox.

  4. I am copying the files to another directory. By this:

    File.Copy(allFiles[i],fullPath+fullName+"-AA"+nameString+ext);
    
  5. Now I want to delete the files from the directory. For this I am doing this:

    File.Delete(allFiles[i]);
    

But its giving me this error:

The process cannot access the file 'C:\G\a.jpg' because it is being used by another process.

Please tell me how to resolve this? I didn't attach the full code here because it'll be large. Please ask me if you want to see any part of my code.


回答1:


Chances are you are loading the image directly from the file. For example,

PictureBox[i] = Image.FromFile(allFiles[i]);

If you look up the documentation for the Image.FromFile method, you will find that it actually locks the file until the Image is disposed. (In fact, most other loading methods in the Image class also locks the file until the Image is disposed.)

So to work around this problem, copy the picture file contents to memory and load it from there. For example,

PictureBox[i] = Image.FromStream(new MemoryStream(File.ReadAllBytes(allFiles[i])));

That way, the file itself will remain unlocked and you can freely move/delete it.




回答2:


Of course it's being used.

Copy the files to another directory first (Step 4),

Delete the old directory

then do the third step (assigning it to a array and loading it to PictureBox) from the newly copied directory.

Alternative:

You must close the stream handler before deleting the files..

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
 using (PictureBox[i] = Image.FromStream(fs))
 {
  ...
 }


来源:https://stackoverflow.com/questions/23465794/cannot-delete-files-from-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!