1

I've written a simple (console)script in C# that recursively deletes files and folders in the given parameter ex: delete_folder.exe "C:\test"

I use this tiny piece of code during an uninstall to delete the remaining files after the uninstall. The code on itself works fine, but I receive the error: System.IO.IOException: The process cannot access the file 'C:\test\test2' because it is being used by another process.

Just before this error the uninstaller stops and deletes a couple of services (created by the installer)

It seems to me that Windows still uses the folder test2. So my question is: How to check if a folder is in use by another process and how to stop that process from being there, to be able to delete the remaining folders.

The console application looks like this:

class Program
    {
        public static void log(string t)
        {
            File.AppendAllText("C:\\testlog.txt", DateTime.Now.ToString() + "----" + t + "\r\n");
        }
        static void Main(string[] args)
        {
            try
            {
                string path = args[0];
                if (Directory.Exists(path) == true)
                {
                    Directory.Delete(path, true);
                }
                else
                {
                    Console.WriteLine("Dir not found!");
                }
            }
            catch (Exception ex)
            {
                log(ex.ToString());
            }
        }
    }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Guido Visser
  • 2,209
  • 5
  • 28
  • 41

1 Answers1

1

A try...catch might sound not too elegant (actually, basing the normal flow of an algorithm on this statement is inadvisable in most of the cases), but seems the only way through here. Bear in mind that there is no System.IO (direct) property telling whether an element is in use; and thus relying on this is the usual solution for this kind of problems (post about file in use). Sample code:

foreach (string dir in System.IO.Directory.GetDirectories(rootDirectory))
{
    try
    {
        System.IO.Directory.Delete(dir);
    }
    catch
    {
        //There was a problem. Exit the loop?
    }
}
Community
  • 1
  • 1
varocarbas
  • 12,354
  • 4
  • 26
  • 37