Cannot delete files from a directory

2019-08-13 02:54发布

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.

2条回答
我想做一个坏孩纸
2楼-- · 2019-08-13 03:16

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))
 {
  ...
 }
查看更多
等我变得足够好
3楼-- · 2019-08-13 03:22

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.

查看更多
登录 后发表回答