且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法从目录中删除文件

更新时间:2023-12-04 19:57:22

很可能是直接从文件加载图像。例如,

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

如果您查找 Image.FromFile 方法,你会发现它实际上锁定文件,直到 Image 被处置。 (事实上​​, Image 类中的大多数其他加载方法也会锁定文件,直到 Image 被处理。)



因此,为了解决这个问题,将图片文件内容复制到内存并从那里加载。例如,

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

这样,文件本身将保持解锁状态,您可以***移动/删除它。 >

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.

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.