c#使用参数运行cmd并在完成时关闭它

时间:2016-10-26 14:16:33

标签: c# cmd

System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.FileName = "cmd.exe";
        startInfo.WorkingDirectory = @"C:\";
        startInfo.Arguments = "dir / s / b / o:n / A:D";
        process.StartInfo = startInfo;
        process.Start();

我尝试使用参数运行cmd,但它不起作用...

2 个答案:

答案 0 :(得分:2)

请参阅cmd.exe /?cmd.exe没有参数dir

正确的语法是cmd.exe /c dir。此外,您的命令行键还有额外的空间:" / s"而不是" / s"等等:

    startInfo.FileName = "cmd.exe";
    startInfo.Arguments = "/c dir /s /b /o:n /A:D";

答案 1 :(得分:1)

删除spaces和字母之间的/,如下所示:

System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.FileName = "cmd.exe";
            startInfo.WorkingDirectory = @"C:\";
            startInfo.Arguments = "/c dir /s /b /o:n /A:D";
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();

等待该过程结束使用process.WaitForExit();