Reputation: 2869
I want to delete all *.tmp files in a temp folder in my C# application.
The code to execute DEL command using cmd.exe is taking forever. It stays at Process.WaitForExit()
forever and Process.HasExited
remains false. But the same command runs well if used manually in cmd:
DEL /Q /F "C:\Users\WinUser\AppData\Local\Temp\abc\*.tmp"
Code:
Process Process = new Process();
Process.StartInfo.FileName = "cmd.exe";
Process.StartInfo.Arguments = " DEL /Q /C /F \"C:\\Users\\WinUser\\AppData\\Local\\Temp\\abc\\*.tmp\"";
Process.StartInfo.CreateNoWindow = true;
Process.StartInfo.UseShellExecute = false;
Process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
Process.Start();
Process.WaitForExit();
while (!Process.HasExited)
{
MessageBox.Show("Error");
}
**Note: My mistake was that I was using /C after DEL and the correct command line is:
Process.StartInfo.Arguments = " cmd /C DEL /Q /F \"C:\\Users\\WinUser\\AppData\\Local\\Temp\\abc\\*.tmp\"";
Though, I will switch to .NET framework based deletion code mentioned below. But I initially selected command line (cmd.exe) based operation because Process.WaitForExit()
does not hang program while execution. I have 1000+ files to delete in the delete operation.
Upvotes: 2
Views: 4688
Reputation: 31848
Don't use shell out (use the Process object) to do something you could do with native .Net objects.
DirectoryInfo tempDir = new DirectoryInfo("C:\\Users\\WinUser\\AppData\\Local\\Temp\\abc\\");
foreach (FileInfo tempFile in tempDir.GetFiles())
{
tempFile.Delete();
}
See:
Upvotes: 4
Reputation: 22073
I'd rather do:
string[] files = Directory.GetFiles("C:\\Users\\WinUser\\AppData\\Local\\Temp\\abc", "*.tmp");
foreach (string filename in files)
File.Delete(filename);
Because .Net has equivalent functionality
Also with the SearchOption.AllDirectories
all sub-directory "*.tmp"
files can be deleted also.
Upvotes: 1
Reputation: 43254
You need to add a /C to the arguments:
Process.StartInfo.Arguments = "/C DEL /Q /F \"C:\\Users\\WinUser\\AppData\\Local\\Temp\\abc\\*.tmp\"";
Otherwise it will just run cmd.exe and never exit.
Upvotes: 8