简体   繁体   English

无法从目录中删除文件

[英]Cannot delete files from a directory

I am describing my work process bellow: 我在描述我的工作流程如下:

  1. I get image files from a directory. 我从目录获取图像文件。

  2. Creating a PictureBox array for displaying the images. 创建一个PictureBox数组以显示图像。

  3. Creating a Image array from the files that I got from the directory. 根据我从目录中获得的文件创建一个Image数组。 I am creating this array for making the image source of PictureBox . 我正在创建此数组来制作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. 该进程无法访问文件'C:\\ G \\ a.jpg',因为它正在被另一个进程使用。

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. 如果查看Image.FromFile方法的文档,您会发现它实际上会锁定文件,直到Image.FromFile Image (In fact, most other loading methods in the Image class also locks the file until the Image is disposed.) (实际上, Image类中的大多数其他加载方法也会锁定文件,直到处理掉Image为止。)

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. 这样,文件本身将保持解锁状态,您可以自由移动/删除它。

Of course it's being used. 当然正在使用。

Copy the files to another directory first (Step 4), 首先将文件复制到另一个目录(第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. 然后从新复制的目录执行第三步(将其分配给数组并将其加载到PictureBox)。

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))
 {
  ...
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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