View Single Post
  #1 (permalink)  
Old August 26th, 2008, 12:58 AM
maricar maricar is offline
Authorized User
 
Join Date: Aug 2008
Location: manila, , Philippines.
Posts: 38
Thanks: 1
Thanked 0 Times in 0 Posts
Default Unable to delete file System.IO.Delete error

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();

                }


Reply With Quote