Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

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

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:UsersALI PCDocumentsMy ProjectsDoctor ClinicDoctor ClinicImages1.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:UsersALI PCDocumentsMy ProjectsDoctor ClinicDoctor ClinicFormsReportForm.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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...