Deleting File which is displayed in picturebox

前端 未结 5 1321
北海茫月
北海茫月 2021-01-17 15:39

I am selecting file from openfiledialoge and displaying it in picturebox and its name in textbox when I click on delete button I am getting exception The

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-17 16:06

    I had the same problem : I loaded a file in a PictureBox and when trying to delete it I got the same exception.
    This occurred only when the image was displayed.
    I tried them all :

    picSelectedPicture.Image.Dispose();
    picSelectedPicture.Image = null;
    picSelectedPicture.ImageLocation = null;  
    

    and still got the same exception.
    Then I found this on CodeProject : [c#] delete image which is opened in picturebox.
    Instead of using PictureBox.Load() it creates an Image from the file and sets it as PictureBox.Image:

    ...
    // Create image from file and display it in the PictureBox
    Image image = GetCopyImage(imagePath);
    picSelectedPicture.Image = image;
    ...  
    
    private Image GetCopyImage(string path) {
        using (Image image = Image.FromFile(path)) {
            Bitmap bitmap = new Bitmap(image);
            return bitmap;
        }
    }  
    

    No more exceptions when I delete the file.
    IMHO, this is the most suitable solution.

    EDIT
    I forgot to mention that you can safely delete the file immediately after display :

    ...
    // Create image from file and display it in the PictureBox
    Image image = GetCopyImage(imagePath);
    picSelectedPicture.Image = image;
    System.IO.File.Delete(imagePath);
    ...  
    

提交回复
热议问题