Deleting directory that contains items

I am trying to delete a directory using C#. The first method I tried was

Directory.Delete(@"C:\Program Files (x86)\Qmuzki32");

I get an exception stating that the directory is not empty. I then found a cmd command which I can use to delete the directory quietly regardless of the fact that the directory is empty or not. I ran the following command in cmd:

rmdir /s /q "C:/Program Files (x86)/Qmuzik32"

This worked and did exactly what I wanted it to do. With my first attempt I tried building this command into a C# process like so:

if (Directory.Exists(@"C:\Program Files (x86)\Qmuzik32"))
   {
       string sQM32Folder = @"C:\Program Files (x86)\Qmuzik32";
       Process del = new Process();
       del.StartInfo.FileName = "cmd.exe";
       del.StartInfo.Arguments = string.Format("rmdir /s /q \"{0}\"", sQM32Folder);
       del.WaitForExit();
   }

This did not work and then I tried it like this:

if (Directory.Exists(@"C:\Program Files (x86)\Qmuzik32"))
   {
       string sQM32Folder = @"C:\Program Files (x86)\Qmuzik32";
       Process del = new Process();
       del.StartInfo.FileName = "rmdir.exe";
       del.StartInfo.Arguments = string.Format("/s /q \"{0}\"", sQM32Folder);
       del.WaitForExit();
   }

Same problem. I get the exception:

No process is associated with this object.

I do think I am on the right track; maybe the code above just requires some tweaking.

Answers


Just use Directory.Delete(string, bool).

While the low-level filesystem APIs of course require you to make sure the directory is empty first, any half-decent framework abstracting them allows you do do a recursive delete. In fact, existence of such a method would be the first thing I'd check before even trying to resort to external programs.


If you want to use the cmd way you can use this:

ProcessStartInfo Info = new ProcessStartInfo(); 
Info.Arguments = "/C rd /s /q \"C:\\Program Files (x86)\\Qmuzik32\""; 
Info.WindowStyle = ProcessWindowStyle.Hidden; 
Info.CreateNoWindow = true; 
Info.FileName = "cmd.exe"; 
Process.Start(Info);

del.Start();
del.WaitForExit();

you didn't start the procces so it doesn't have a PID so it dies


Need Your Help

Outlook Folder Browse Dialog?

c# visual-studio-2008 outlook vsto

I'm hoping someone could help me with a quick point in the right direction. ALL I NEED is the Outlook folder browser dialog call. I am developing some plugins for Outlook using C# and this is a cru...

Python - shutil seems to be not making a true binary copy of a file

python copy shutil

Following the excellent advice of a poster yesterday I started using the shutil.copyfileobj method to make a copy of a file.