将图像用作 PictureBox 的源后,如何从文件夹中删除这些图像? [英] How do I delete the images from a folder after they have been used as the source for a PictureBox?

查看:19
本文介绍了将图像用作 PictureBox 的源后,如何从文件夹中删除这些图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

链接到我的上一个问题,提供了背景信息

我通过以编程方式更改保存附件的临时文件夹中的图像来回答我自己的上述问题.在解决我自己的问题时,这给我带来了一个新问题,我觉得这与前者过于分离.

I answered my own question above by programmatically changing images from the tempory folder where attachments are saved. This caused a new issue for me when fixing my own problem that I feel is too separate from the former.

当我的程序关闭时,我从临时目录中删除了图像.因为我在点击不同的图像时预览可以正常工作.尝试关闭程序时出现以下错误(在此事件中删除图像):

As my program closes, I delete the images from the temporary directory. Since I have got the preview to work fine upon clicking on the different images. I get the following error when trying to close the program (the deleting of images happens on this event):

进程无法访问文件c: empDigitalArchiveFILENAME.jpg",因为它正被另一个进程使用.

The process cannot access the file 'c: empDigitalArchiveFILENAME.jpg' because it is being used by another process.

所以我试图通过事先从临时文件夹中清除图片来解决它:

So I have attempted to resolve it by clearing the picture from the temp folder before hand via:

if (picAttachPreview.Image != null)
        {
            picAttachPreview.Image.Dispose();
            picAttachPreview.Refresh();
        }

        //Runs through each file in the temporary directory and removes them to clear folder
        foreach (string item in Directory.GetFiles(tempfolder))
        {
            File.Delete(item);
        }

我觉得我应该显示图像更新的位置以供参考:

I feel I should show where the image is updated for reference:

if (chkAttachments.Text.Contains(".jpg"))
        {
            var selectedImage = chkAttachments.Text;
            picAttachPreview.Image = Image.FromFile(Path.Combine(tempfolder, selectedImage));
        }

推荐答案

Image.FromFile 保持文件在使用中.您可以使用 Image.FromStream 代替.

var file = @"d:pic1.jpg";
using (var s = new System.IO.FileStream(file, System.IO.FileMode.Open))
{
    pictureBox1.Image = Image.FromStream(s);
}
System.IO.File.Delete(file);

这篇关于将图像用作 PictureBox 的源后,如何从文件夹中删除这些图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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