2

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.

4

3 回答 3

9

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.

于 2012-06-11T11:18:13.930 回答
6

如果你想使用 cmd 方式,你可以使用这个:

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);
于 2012-06-11T11:23:49.307 回答
4
del.Start();
del.WaitForExit();

你没有启动procces所以它没有PID所以它死了

于 2012-06-11T11:19:57.827 回答