Windows – Try to delete files used by IIS

iis-7.5iowindowswindows-server-2008-r2

I got a service coded in c# whoes deleted somes web site files hosted on iis, before an update. But sometime when i delete the files, they stay there.

If I try to delete them manually, via explorer, the file are not deletable, because they are in state "Delete pending".

There is the way my service try to delete the file

 try
                {
                  // Enlève tout les attributs sur le fichiers afin de s'assurer que le fichier n'est pas en lecture seul
                  File.SetAttributes(file, FileAttributes.Normal);

                  // Supprime le fichier
                  File.Delete(file);
}

It's there a way to avoid this state ?

What can i do to force the delete by c# code?

Could i release all process to the file by c# code ?

The environnement is

IIS 7.5
Windows 2008-r2
.net 4.0

Thanks

Best Answer

You'll want to find out what other process has the files open. I don't know how you'd do that programatically, but speaking as a sysadmin, the handle.exe utility from SysInternals (or their Process Explorer GUI tool) can show that to you real-time.

Then you'll want to either:

  1. Avoid the condition that causes the file to be locked by the other process,
  2. Close the handle if you can do so safely.