我可以在C#中执行以下操作:
var pSpawn = new Process
{
StartInfo = { WorkingDirectory = @"C:\temp", FileName = fileToRun, CreateNoWindow = true }
};
pSpawn.Start();
这很好....但是我想知道是否有办法运行命令(即:“dir / b”)而不必将其封装在批处理文件中?
答案 0 :(得分: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());
答案 1 :(得分:2)
你可以这样打电话:
ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
info.Arguments = "/c dir /b";
Process.Start(info);