Himesh
Himesh

Reputation: 458

How to delete file after closed that file process in C#

I want to delete a file. But it cannot do because it use another process. Error message :

"The process cannot access the file '*file path\4.JPG*' because it is being used by another process."  

My program's description is,suppose I copy a image into one common file. then if I want to delete ths image from common folder, then error message will generate. file.Delete(..) is not working in my code.

    private void btnDelete_Click(object sender, EventArgs e)
    {
        DialogResult result = MessageBox.Show("Are you sure do you want to delete this recorde?","Delete",MessageBoxButtons.YesNo,MessageBoxIcon.Question);

        if (result.ToString().Equals("Yes"))
        {
            string deleteQuery = "DELETE FROM dbo.fEmployee WHERE EmpId=@empId";
            SqlParameterCollection param = new SqlCommand().Parameters;
            param.AddWithValue("@empId",cmbEmpIdD.SelectedValue);
            int delete = _dataAccess.SqlDelete(deleteQuery,param);
            if (delete>0)
            {
                **ImageDeletion();**
                MessageBox.Show("Recorde Deleted sucessfully.","Delete",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
            else if (delete.Equals(0))
            {
                 MessageBox.Show("Recorde is not deleted.","Falied",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
        }
    }


    private void ImageDeletion()
    {
        string ext;
        ext = Path.GetExtension(txtImgPathD.Text.Trim());
        if (!string.IsNullOrWhiteSpace(ext))
        {
            string path = appPath + @"\" + @"EmployeeImages\" + cmbEmpId.SelectedValue.ToString().Trim() + ext;
            PictureBox.InitialImage = null;
            PictureBox.Invalidate();
            PictureBox.Image = null;
            PictureBox.Refresh();
            File.Delete(path);
        }
    }

Please give me a solution for the delete a file part. Thank you!

Upvotes: 2

Views: 1586

Answers (2)

Isuru
Isuru

Reputation: 31283

Try disposing the image in the PictureBox.

PictureBox.Image.Dispose();

Upvotes: 0

BrianC
BrianC

Reputation: 314

The error message here is telling you all you need to know - something has hold of your file so you cannot delete it.

Have you opened the file elsewhere in your application and not closed the filestream correctly, perhaps?

Upvotes: 1

Related Questions