该进程无法访问该文件,因为在删除添加到图像列表和列表视图的文件时该文件正在被另一个进程使用

问题描述 投票:0回答:1

我想将图像文件加载到文件夹中,然后将它们添加到图像列表中,然后将其分配给列表视图以获取我单击的项目的缩略图样式,它显示在图片框中。当我想删除文件时,我将图像框的图像属性设置为空,然后我将从列表视图和图像列表中删除图像项,然后继续删除文件,出现错误“进程无法访问文件”路径到图像文件”,因为它正在被另一个进程使用。

加载填充图像列表和列表视图的图像的代码:

 private void LoadImages(string path)
 {
     try
     {
         imageList = new ImageList() { ColorDepth = ColorDepth.Depth32Bit, ImageSize = new Size(194, 194), TransparentColor = Color.Transparent };
         listView.LargeImageList = imageList;

         IEnumerable<string> files = Directory.EnumerateFiles(path, "*.*", SearchOption.TopDirectoryOnly);         

         foreach (string file in files)
         {
                 AddImage(file);
         }
         if (listView.Items.Count > 0)
         {
             string firstImage = listView.Items[0].ImageKey;
             selectedPicBox.Image = Image.FromFile(firstImage);
             selectedPicBox.ImageLocation = firstImage;
         }
     }
     catch (Exception ex)
     {
         Program.EventLog.WriteEntry($"Scan-Loading scans : {ex}", EventLogEntryType.Error, 101);
         throw;
     }
 }

添加图片的代码:

imageList.Images.Add(path, Image.FromStream(new MemoryStream(File.ReadAllBytes(path)), true, false));
    listView.Items.Add(path, file.Name, path);  

删除图像的代码:

string path = listView.SelectedItems[0].ImageKey;
selectedPicBox.Image = null;
selectedPicBox.ImageLocation = null;

listView.SelectedItems.Clear();
listView.Items.RemoveByKey(path);

imageList.Images[path].Dispose();
imageList.Images.RemoveByKey(path);

File.Delete(path);
c# listview thumbnails imagelist file-in-use
1个回答
0
投票

问题是你正在这样做:

selectedPicBox.Image = Image.FromFile(firstImage);

在填充

ImageList
时,您避免调用该方法,但您可以在那里执行此操作。这将锁定该文件,直到您处置该
Image
对象。,但您永远不会这样做。你有这个:

selectedPicBox.Image = null;

但这没有帮助,因为只会停止显示

Image
。它不会处置它。如果你打算这样做,你需要先这样做:

selectedPicBox.Image.Dispose();

不过你不应该这样做。这太疯狂了:

selectedPicBox.Image = Image.FromFile(firstImage);
selectedPicBox.ImageLocation = firstImage;

ImageLocation
属性的全部意义在于能够通过仅提供文件路径来显示
Image
,而不必自己创建
Image
。你应该选择其中之一,而不是两者都做。如果您想避免锁定文件,您应该执行后者。

简而言之,设置

ImageLocation
并且不要调用
Image.FromFile
。尽管如此,请务必在使用完所有支持的对象上调用
Dispose
。它可能不是必需的,但它可以使您的应用程序更加高效并可以避免一些异常。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.