So I am using C# and am making an enrollment system. So there is an option to add a picture and what I do, I prompt the user to pick a file and that file will then be Copied to the Directory folder and then renamed into the student's admission number. Here is the code for that browse button:
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.Filter = "All JPEG files (*.jpg; *.jpeg)| *.jpg; *.jpeg";
string filter = openDlg.Filter;
openDlg.Multiselect = false;
openDlg.Title = "Open a JPG File";
if (openDlg.ShowDialog() == DialogResult.OK)
{
curFileName = openDlg.SafeFileName;
string curFilePath = openDlg.FileName;
openDlg.Dispose();
string sourcePath = @curFilePath.Remove((curFilePath.Length - curFileName.Length));
string targetPath = "@";
mycon.Open();
string cmdstr = "SELECT imageDirectory from userSettings WHERE ID = 1";
cmd = new OleDbCommand(cmdstr, mycon);
dr = cmd.ExecuteReader();
while (dr.Read())
{
targetPath = (@dr["imageDirectory"].ToString());
}
dr.Close();
mycon.Close();
string sourceFile = Path.Combine(sourcePath, curFileName);
string destFile = Path.Combine(targetPath, curFileName);
File.Copy(sourceFile, destFile, true);
newname = @destFile.Remove((destFile.Length - curFileName.Length)).ToString() + "\\" + (DateTime.Now.Year + "-" + textBox1.Text+".jpeg");
if (File.Exists(newname) == true)
{
pictureBox1.Image.Dispose();
try
{
File.Delete(newname);
}
catch (IOException ex)
{
MessageBox.Show(ex.ToString());
return;
}
}
File.Move(destFile, newname);
photoPath = newname;
pictureBox1.Image = Image.FromFile(photoPath);
The problem are:
a.) I have a function to allow the user to go to the next step and then if he wants to do some changes in the last step he could go back and update it. The problem here is when he changes the picture, I get an error stating "The file cannot be accessed because it is being used by another process"
b.) When the user already uploaded a picture and then went back to the home page, he won't be able to upload a new picture when he decides to enroll again as well with an error stating: "The file cannot be accessed because it is being used by another process".
The two errors both point here :
`File.Delete(newname);`
I really don't know what to do guys I have been looking for a solution to this since last night and I can't see a solution that wouldn't get me to change the whole code altogether. please help :(