io - How to delete file and that file is used by another process using C# -


in c# application want delete file in below scenario.

  1. openfiledialog , select .jpg file.

  2. display file in picturebox.

  3. delete file if needed.

i try while doing step 3 set default image picturebox before delete not work.

how can delete file? please suggest me.

 // code select file.  private void btnselet_click(object sender, eventargs e)  {         if (dialogresult.ok == openfiledialog1.showdialog())         {             txtfilename.text = openfiledialog1.filename;             mypicturebox.image = image.fromfile(openfiledialog1.filename);         }  }   // code delete file  private void btndelete_click(object sender, eventargs e)  {         try         {             //mypicturebox.image = image.fromfile(system.io.directory.getcurrentdirectory() + @"\images\defaultimage.jpg");             system.io.file.delete(txtfilename.text);             messagebox.show("file delete sucessfully");         }         catch(exception ex)         {             messagebox.show(ex.message);         }  } 

replacing image sounds idea - don't forget dispose of old image that's still holding file open (and will, default, until image garbage collected - @ unknown time in future):

private void btndelete_click(object sender, eventargs e)  {         try         {             var old = mypicturebox.image;             mypicturebox.image = image.fromfile(system.io.directory.getcurrentdirectory() + @"\images\defaultimage.jpg");             old.dispose();              system.io.file.delete(txtfilename.text);             messagebox.show("file delete sucessfully");         }         catch(exception ex)         {             messagebox.show(ex.message);         }  } 

(it may possible dispose of image directly without replacing image picturebox - depends on else you're going after deletion - e.g. if form on picturebox appears closing may want let happen first , directly dispose of image).


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -