Help! I can’t figure out how to close the file. It always gives me IOException file, something like it is being used by another process
Here’s my 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 the file ‘C:\Pictures\Copied.jpg’ because it is being used by another process.
Image.FromFile() puts a write lock on the file. Form1_Load() thus puts a lock on Copied.jpg. You then press the uploadpic_btn button to assign a new bitmap to the BackgroundImage property. Next pressing saveBTN is however likely to fail the way you’ve written the code. Copied.jpg is still locked, the Image object still exists. It doesn’t disappear until the garbage collector runs.
To avoid waiting for this, you’ll have to dispose the image. Fix: