How to delete a file and this file is in use by another process using C #
In my C # application, I want to delete a file in below script.
-
OpenFileDialog and select any .jpg file.
-
Display this file in a PictureBox.
-
Delete this file if necessary.
I am already trying to do step 3 I installed the default Image in the PictureBox before uninstalling, but it doesn't work.
How do I delete a file? Please suggest me.
// Code for select file.
private void btnSelet_Click(object sender, EventArgs e)
{
if (DialogResult.OK == openFileDialog1.ShowDialog())
{
txtFileName.Text = openFileDialog1.FileName;
myPictureBox.Image = Image.FromFile(openFileDialog1.FileName);
}
}
// Code for Delete file
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
//myPictureBox.Image = Image.FromFile(System.IO.Directory.GetCurrentDirectory() + @"\Images\defaultImage.jpg");
System.IO.File.Delete(txtFileName.Text);
MessageBox.Show("File Delete Sucessfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
source to share
Replacing the image sounds like a good idea - but remember to get rid of the old Image
one that still keeps the file open (and will be the default until Image
garbage collected - at some unknown time in the future):
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
var old = myPictureBox.Image;
myPictureBox.Image = Image.FromFile(System.IO.Directory.GetCurrentDirectory() + @"\Images\defaultImage.jpg");
old.Dispose();
System.IO.File.Delete(txtFileName.Text);
MessageBox.Show("File Delete Sucessfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
(It is also possible Dispose
Image
directly without replacing the image for PictureBox
- it depends on what else you are going to do after deleting - for example, if the form that PictureBox
appears on that you can let this happen first and then just delete the image).
source to share