无法删除列表视图中显示的图像文件 [英] Cannot delete an image file that is shown in a listview

查看:100
本文介绍了无法删除列表视图中显示的图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的列表视图中,我显示某个文件夹中小图像的缩略图.我将listview设置如下:

In my listview I show thumbnails of small images in a certain folder. I setup the listview as follows:

var imageList = new ImageList();
foreach (var fileInfo in dir.GetFiles())
{
    try
    {
        var image = Image.FromFile(fileInfo.FullName);
        imageList.Images.Add(image);
    }
    catch
    {
        Console.WriteLine("error");
    }
}

listView.View = View.LargeIcon;
imageList.ImageSize = new Size(64, 64);
listView.LargeImageList = imageList;

for (int j = 0; j < imageList.Images.Count; j++)
{
    var item = new ListViewItem {ImageIndex = j, Text = "blabla"};
    listView.Items.Add(item);
}

用户可以右键单击列表视图中的图像以将其删除.我从列表视图中将其删除,然后从文件夹中删除该图像.现在,我得到文件正在使用的错误.当然,这是合乎逻辑的,因为图像列表正在使用该文件.

The user can rightclick on an image in the listview to remove it. I remove it from the listview and then I want to delete this image from the folder. Now I get the error that the file is in use. Of course this is logical since the imagelist is using the file.

我试图首先从图像列表中删除图像,但是我一直保持文件锁定.

I tried to first remove the image from the imagelist, but I keep on having the file lock.

有人可以告诉我我在做什么错吗?

Can somebody tell me what I am doing wrong?

谢谢!

推荐答案

您需要将文件加载到MemoryStream中,如下所示:

You need to load the file into a MemoryStream, like this:

var image = Image.FromStream(new MemoryStream(File.ReadAllBytes(fileInfo.FullName)));

这样,该文件将只被读取一次,并且不会保持锁定状态.

This way, the file will only be read once, and will not remain locked.

您正在将图像加载到ImageList中.
由于ImageList会复制其图像,因此您应该立即处置原始文档,如下所示:

You're loading the images into an ImageList.
Since the ImageList makes copies of its images, you should simply dispose the originals right away, like this:

using (var image = Image.FromFile(fileInfo.FullName))
    imageList.Images.Add(image);

这篇关于无法删除列表视图中显示的图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆