简体   繁体   English

使用cmd.exe执行DEL命令的代码将永远存在

[英]The code to execute DEL command using cmd.exe is taking forever

I want to delete all *.tmp files in a temp folder in my C# application. 我想删除C#应用程序中临时文件夹中的所有* .tmp文件。

The code to execute DEL command using cmd.exe is taking forever. 使用cmd.exe执行DEL命令的代码将永远存在。 It stays at Process.WaitForExit() forever and Process.HasExited remains false. 它永远停留在Process.WaitForExit()并且Process.HasExited保持为false。 But the same command runs well if used manually in cmd: 但是如果在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: **注意:我的错误是我在DEL之后使用/ C并且正确的命令行是:

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. 不过,我将切换到下面提到的基于.NET框架的删除代码。 But I initially selected command line (cmd.exe) based operation because Process.WaitForExit() does not hang program while execution. 但我最初选择了基于命令行(cmd.exe)的操作,因为Process.WaitForExit()在执行时不会挂起程序。 I have 1000+ files to delete in the delete operation. 我在删除操作中要删除1000多个文件。

You need to add a /C to the arguments: 您需要在参数中添加/ C:

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. 否则它只会运行cmd.exe而永远不会退出。

Don't use shell out (use the Process object) to do something you could do with native .Net objects. 不要使用shell out(使用Process对象)来执行可以使用本机.Net对象执行的操作。

DirectoryInfo tempDir = new DirectoryInfo("C:\\Users\\WinUser\\AppData\\Local\\Temp\\abc\\");

foreach (FileInfo tempFile in tempDir.GetFiles())
{
    tempFile.Delete();
}

See: 看到:

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 因为.Net具有同等的功能

Also with the SearchOption.AllDirectories all sub-directory "*.tmp" files can be deleted also. 此外,使用SearchOption.AllDirectories也可以删除所有子目录"*.tmp"文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM