:Unable to delete file System.IO.Delete error

Aug 25 2008 11:22 PM

I have a program that creates a directory (C:\\Temp) where image files are being saved. My form closing event will clean up the image files, however it throws an exception..”The process cannot access the file x.jpg because it is being used by another process”..When I open the temp folder almost all of files saved there are deleted except for one(x.jpg)..How can I stop the “another process” from locking this file…

I used this code:

 

 

            foreach (string picturePath in System.IO.Directory.GetFiles(“C:\\Temp”, "*.jpg"))

            {

               

                try

                {

                    Process[] myProcesses;

                    myProcesses = Process.GetProcessesByName("Outlook");

                    foreach (Process myProcess in myProcesses)

                    {

                        myProcess.CloseMainWindow();

                    }

 

                    FileStream fs = File.Open(picturePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Delete);

                    File.Delete(picturePath);

                    fs.Close();

                    fs.Dispose();

 

                }


Answers (4)