My code goes as follows:
private void btnChangeImg_Click(object sender, EventArgs e)
{
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 here
}
else
openFileDialogForImgUser.Dispose();
}
}
}
}
I can't copy the file because System.IO.IOException
occurs. The message goes like: "The process cannot access the file <file> because it is being used by another process". I know I have to terminate the process using the file, but how do I know which process that is? BTW, when I say file, I am refering to the image that the user selected when the OpenFileDialog is shown.