1

我可以在 C# 中执行以下操作:

var pSpawn = new Process
     {
         StartInfo = { WorkingDirectory = @"C:\temp", FileName = fileToRun, CreateNoWindow = true }
     };
     pSpawn.Start();

这很好用....但是我想知道是否有一种方法可以运行命令(即:“dir / b”)而不必将其封装在批处理文件中?

4

2 回答 2

3

只需启动 cmd.exe 并传递所需的参数

 var pSpawn = new Process
 {
     StartInfo = 
     { 
         WorkingDirectory = @"C:\temp", 
         FileName = "cmd.exe", 
         Arguments ="/K dir /b" }
 };

 pSpawn.Start();

我添加了参数/K以使命令窗口保持打开状态,因此可以看到命令的输出dir
当然,我认为您真的有兴趣捕捉命令的输出。
在这种情况下,您可以使用以下内容:

StringBuilder sb = new StringBuilder();
var pSpawn = new Process
{
     StartInfo = 
     { 
        WorkingDirectory = @"C:\temp", 
        FileName = "cmd.exe", 
        Arguments ="/c dir /b", 
        CreateNoWindow = true,
        RedirectStandardOutput = true,
        RedirectStandardInput = true,
        UseShellExecute = false
     }
};

pSpawn.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
pSpawn.Start();
pSpawn.BeginOutputReadLine();
pSpawn.WaitForExit();
Console.WriteLine(sb.ToString());
于 2013-04-25T12:05:04.157 回答
2

你可以这样称呼:

ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
info.Arguments = "/c dir /b";
Process.Start(info);
于 2013-04-25T12:05:46.463 回答