C# File.Delete, file being used by another process

cerror handling

I have a problem when I'm trying to delete an image file.
I always get an error that says: IOExeption was unhandled. Acces denied because the file is beining used by another process.

I do'nt know what process that could be and how to solve it.

private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {            
            Album album = GetAlbum(comboBox1.SelectedIndex);
            Photo photo = GetPhoto(comboBox1.SelectedIndex, comboBox3.SelectedIndex);           

            txtPhotoPath.Text = Directory.GetCurrentDirectory() + "\\"  + photo.SPath;

            lblExtention.Text = photo.SExtention;
            txtPhotoTitle.Text = photo.STitle;
            pctrbFoto.Image = Image.FromFile(foto.SPath).GetThumbnailImage(GetWitdth(photo.SPath, GetHeight(photo.SPath, 150)), GetfHeight(photo.SPath, 150), null, new IntPtr());
        }

private void btnChangePhoto_Click(object sender, EventArgs e)
{
            Album album = GetAlbum(comboBox1.SelectedIndex);
            Photo photo = GetPhoto(comboBox1.SelectedIndex, comboBox3.SelectedIndex);

            File.Delete("Albums\\Images\\" + photo.STitle + foto.SExtention);

            photo.SExtention = lblExtention.Text;
            photo.STitle = txtPhotoTitel.Text;
            Photo.SPath = txtPath.Text;

            File.Copy(photo.SPath, "Albums\\Images\\" + photo.STitle + photo.SExtention);

}

Thanks,
Vinzcent


Thanks to all for the help.

I used this and it works very well now


your process is the one that uses file , you need to set image to null use something like this :

var img = Image.FromFile(foto.SPath).GetThumbnailImage(GetWitdth(photo.SPath,
GetHeight(photo.SPath, 150)), GetfHeight(photo.SPath, 150), null, new IntPtr());

pctrbFoto.Image = img;

img = null;

GC.Collect();

Best Answer

The first area I would look is in your GetPhoto method. Do you have a StreamReader that hasn't been closed? Make sure that if you're doing any sort of I/O on the file prior to the delete that you close those connections first. What does the GetPhoto() method do?