1
votes

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);
2
this link is for vb.net i'm using c# @AjayKumarprog ahmed
bro then you should add a vbNet label in your questions as well.Ajay Kumar
@progahmed The framework is the same, though, so the exceptions and solutions are identical. Just the programming syntax is different.Nyerguds

2 Answers

0
votes

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
votes

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