c#运行带有参数的CMD,并在结束时关闭它

本文关键字:结束 行带 运行 参数 CMD | 更新日期: 2023-09-27 18:15:08

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,但它不工作…

c#运行带有参数的CMD,并在结束时关闭它

删除/和字母之间的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();

参见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";