How do I delete the images from a folder after they have been used as the source for a PictureBox? [duplicate]

和自甴很熟 提交于 2019-12-18 09:08:26

问题


Link to my previous question, which gives background to the situation

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):

The process cannot access the file 'c:\temp\DigitalArchive\FILENAME.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);
        }

Edit: 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));
        }

回答1:


Image.FromFile keeps the file in use. You can use Image.FromStream instead.

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


来源:https://stackoverflow.com/questions/38829226/how-do-i-delete-the-images-from-a-folder-after-they-have-been-used-as-the-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!