error when i'm trying to delete an image used in a picturebox

∥☆過路亽.° 提交于 2021-02-05 08:09:21

问题


I'm using visual studio 2013 to create a c# windows application and I'm facing this error.

When I'm trying to delete an image that I have been using in a picturebox this error message appears..:

System.IO.IOException: The process cannot access the file 'C:\Users\ALI PC\Documents\My Projects\Doctor Clinic\Doctor Clinic\Images\1.jpg' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at Doctor_Clinic.Forms.ReportForm.deleteBtn_Click(Object sender, EventArgs e) in c:\Users\ALI PC\Documents\My Projects\Doctor Clinic\Doctor Clinic\Forms\ReportForm.cs:line 94

var file = @image;
using (var s = new System.IO.FileStream(file, System.IO.FileMode.Open))
{
    PatientImage.Image = Image.FromStream(s);
}
PatientImage.Image = null;
PatientImage.Image.Dispose();
System.IO.File.Delete(file);

回答1:


Your title is misleading. The line that throws is not the Delete but the Dispose.

You have already set it to null, so you can't Dispose of it any more. Use this instead:

   ..
   if (PatientImage.Image != null)
   {
      Image dummy = PatientImage.Image; 
      PatientImage.Image = null; 
      dummy.Dispose(); 
   }
   ..

First we store a new dummy reference to the image; then we clear the reference from the control and finally we use the dummy reference to free the GDI resources.

This is also recommended whenever you want to set a new Image to a PictureBox.

(This looks a little more complicated than one would expect when dealing with reference variables; but that is not what PictureBox.Image is. It is a property with all sorts of extras going on behind the scenes..)




回答2:


You have your image used by another application on your machine or by another running job. To be sure that no one is using the image restart your pc and retry. If that doesn't work check the permission of the file



来源:https://stackoverflow.com/questions/57754206/error-when-im-trying-to-delete-an-image-used-in-a-picturebox

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