如何重定向cmnd输出

时间:2013-04-09 10:58:09

标签: c# process

我想启动一个cmd文件并将输出重定向到控制台,但它不起作用。我该怎么办?我已设置startInfo.RedirectStandardOutput = true

com = "Parameter";

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = 
    new System.Diagnostics.ProcessStartInfo();

startInfo.FileName = Properties.Settings.Default.pathTo+ @"\Make\copy.cmd";
startInfo.Arguments = com;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
output = process.StandardOutput;
string ln;

while ((ln = output.ReadLine()) != null)
{
    Console.WriteLine(line);
}
process.WaitForExit();

2 个答案:

答案 0 :(得分:1)

来自MSDN

设置startInfo.UseShellExecute = false;

然后你可以把输出作为

Console.WriteLine(process.StandardOutput.ReadToEnd());

答案 1 :(得分:0)

现在,我有了这个解决方案:

                com = "Parameter";;

                System.Diagnostics.Process process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.FileName = Properties.Settings.Default.pathTo + @"\Make\copy.cmd";
                startInfo.Arguments = com;
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError = true;
                startInfo.UseShellExecute = false;
                startInfo.CreateNoWindow = true;
                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit();
                Console.WriteLine(process.StandardOutput.ReadToEnd());
                Console.WriteLine(process.StandardError.ReadToEnd());