Darshan Faldu
Darshan Faldu

Reputation: 1601

How to delete file and that file is used by another process using C#

In my C# application I want to delete file in below scenario.

  1. OpenFileDialog and select any .jpg file.

  2. Display that file in PictureBox.

  3. Delete that file if needed.

I already try while doing step 3 I set default Image to PictureBox just before delete but that is not work.

How can I delete 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);
        }
 }

Upvotes: 0

Views: 3751

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239684

Replacing the image sounds like a good idea - but don't forget to dispose of the old Image that's still holding the file open (and will, by default, until that Image is 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 may also be possible to Dispose of the Image directly without replacing the image for the PictureBox - it depends on what else you're going to do after deletion - e.g. if the form on which the PictureBox appears is closing that you may want to let that happen first and then just directly dispose of the image).

Upvotes: 3

Related Questions