cant delete image because it used by anather process

i cant delete the image after i process to DB ,i dont know how to release it .please look to the code.
thank you
private void btnSave_Click(object sender, EventArgs e)
            DirectoryInfo di = new DirectoryInfo("C:/MyDir");
            FileInfo[] rgFiles = di.GetFiles("*.jpg");
            foreach (FileInfo fi in rgFiles){
                //Read Image Bytes into a byte array
                byte[] imageSampleData = ReadImageToBytes(fi.FullName);
                //Initialize SQL Server Connection
                SqlConnection con = new SqlConnection(txtConnectionString.Text);
                //Set insert query
                string query = "INSERT INTO tblImages (FullPath,MyImageSample) values(@FullPath, @MyImageSample)";
                //Initialize SqlCommand object for insert.
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Parameters.Add(new SqlParameter("@FullPath",
                cmd.Parameters.Add(new SqlParameter("@MyImageSample",
                //Open connection and execute insert query.
                MessageBox.Show("Error while saving image.", "Error");

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Do you want to delete all the images from the directory ?

By the way, fi.Delete() --> which file do you want to delete, because it's outside the loop. It will always contain the latest file :)
mark222Author Commented:
thank Dhaest, no it is inside the loop but forget to copy the last char }.
You can try the following. Add the following items behind con.Close();
(probably one of those will block you)
imageSampleData  = null;
cmd = null;
mark222Author Commented:
not working , still same problem
mark222Author Commented:
it is solved ,the problem because  FileStream fStream was not close.
thank you Dhaest

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.