io - How to delete file and that file is used by another process using C# -
in c# application want delete file in below scenario.
openfiledialog , select .jpg file.
display file in picturebox.
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
Post a Comment