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:
if (open_dialog.ShowDialog() != DialogResult.Cancel)
{
if (uploadpic_pb.BackgroundImage != null) uploadpic_pb.BackgroundImage.Dispose();
uploadpic_pb.BackgroundImage = Image.FromFile(open_dialog.FileName);
// etc...
}
Try using a class level variable for filename instead of targetPath with may be appending a datetime to keep it unique. Keep overwrite = false in the File.copy and see if it works. This is just a test to see that you Copied.Jpg file is in use.
Also - compile the solution in release mode and try running from EXE directly from bin instead of Visual Studio. Sometime the Visual Studio helper process blocks the files.
精彩评论