My code goes like this:
using (var openFileDialogForImgUser = new OpenFileDialog())
{
string location = null;
string fileName = null;
string sourceFile = null;
string destFile = null;
string targetPath = @"..\..\Images";
openFileDialogForImgUser.Filter = "Image Files (*.jpg, *.png, *.gif, *.bmp)|*.jpg; *.png; *.gif; *.bmp|All Files (*.*)|*.*"; // filtering only picture file types
openFileDialogForImgUser.InitialDirectory = @"D:\My Pictures";
var openFileResult = openFileDialogForImgUser.ShowDialog(); // show the file open dialog box
if (openFileResult == DialogResult.OK)
{
using (var formSaveImg = new FormSave())
{
var saveResult = formSaveImg.ShowDialog();
if (saveResult == DialogResult.Yes)
{
imgUser.Image = new Bitmap(openFileDialogForImgUser.FileName); //showing the image opened in the picturebox
fileName = openFileDialogForImgUser.FileName;
location = Path.GetDirectoryName(fileName);
sourceFile = System.IO.Path.Combine(location, fileName);
destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true); /* error occurs at this line */
}
else
openFileDialogForImgUser.Dispose();
}
}
}
What I'm trying to do is that I am prompting the user to select an image in an OpenFileDialog, and copy that picture to a different directory (targetPath, specifically). Everything seems to work fine except for that one line: System.IO.File.Copy(sourceFile, destFile, true);
.
It says that the file is used exclusively used by another process. And that happens for any image I select.
I'm trying to look at others' solution(s) to this problem --- I have to terminate (or wait) for the process that's using my file. If so, how do I do that? Or, if that's not the answer to this, what should I do? Note that this is the only piece of code that deals with image files in my C# solution.