c# - IOException File Copy unhandled. When uploading image from a picturebox -
help! can't figure out how close file. gives me ioexception file, it being used process
here's code
private void uploadpic_btn_click(object sender, eventargs e) { open_dialog = new openfiledialog(); open_dialog.title = "open picture"; open_dialog.filter = "jpeg (*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg"; if (open_dialog.showdialog() != dialogresult.cancel) { uploadpic_pb.backgroundimage = image.fromfile(open_dialog.filename); uploadpic_pb.backgroundimagelayout = imagelayout.stretch; uploadpic_pb.borderstyle = borderstyle.fixedsingle; } } private void savebtn_click(object sender, eventargs e) { string targetpath = path.combine(path.getdirectoryname(application.executablepath), "\\pictures"); string destfile = path.combine(targetpath, "copied.jpg"); if (!directory.exists(targetpath)) { directory.createdirectory(targetpath); } file.copy(open_dialog.filename, destfile, true); } private void form1_load(object sender, eventargs e) { image myimage = image.fromfile(@"c:\pictures\copied.jpg"); uploadpic_pb.backgroundimage = myimage; uploadpic_pb.backgroundimagelayout = imagelayout.stretch; uploadpic_pb.borderstyle = borderstyle.fixedsingle; }
the exception returns
the process cannot access file 'c:\pictures\copied.jpg' because being used process.
image.fromfile() puts write lock on file. form1_load() puts lock on copied.jpg. press uploadpic_btn button assign new bitmap backgroundimage property. next pressing savebtn fail way you've written code. copied.jpg still locked, image object still exists. doesn't disappear until garbage collector runs.
to avoid waiting this, you'll have dispose image. fix:
if (open_dialog.showdialog() != dialogresult.cancel) { if (uploadpic_pb.backgroundimage != null) uploadpic_pb.backgroundimage.dispose(); uploadpic_pb.backgroundimage = image.fromfile(open_dialog.filename); // etc... }
Comments
Post a Comment