2014-10-06 72 views
-2

我的目标是从C#执行一个外部.bat文件。问题是我必须在我的表单中显示执行的Bats的结果,而不是在控制台中。 Google上的解决方案仅向我展示如何启动一个蝙蝠,而不是如何从控制台获取内容。以C#形式运行.Bat

什么可能是最好的方法来实现这一点?

+0

检查这个http://stackoverflow.com/questions/11177554/ c-sharp-bat-file-execution-with-error-output-redirection – 2014-10-06 09:28:30

+0

没有帮助,我想输出整个时间,而不仅仅是完成后。它必须更新蝙蝠生成的每一行 – Horius 2014-10-06 09:32:16

+0

您可以使用proc.StandardOutput.ReadLine()而不是proc.StandardOutput.ReadToEnd()读取每行,因为它是输出 – 2014-10-06 09:34:28

回答

4

您可以在Process类使用StandartOutputEvent:

const string BATFILE = "Test.bat"; 
    const bool HIDE = true; 
    static Encoding ENCODING = Encoding.Default; 

    static void Main(string[] args) 
    { 
     System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd", BATFILE); 

     if (HIDE) 
     { 
      psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
     } 

     psi.RedirectStandardOutput = true; 
     psi.StandardOutputEncoding = ENCODING; 
     psi.UseShellExecute = false; 

     System.Diagnostics.Process p = new System.Diagnostics.Process(); 
     p.StartInfo = psi; 
     p.OutputDataReceived += p_OutputDataReceived; 

     p.Start(); 
    } 

    static void p_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e) 
    { 
     //Do something with a form... 
     System.Console.WriteLine(e.Data); 
    } 
1

我认为你需要需要这个太:

...     
psi.RedirectStandardOutput = true; 
psi.RedirectStandardError = true; 
... 

p.Start(); 

p.checkoutProcess.BeginOutputReadLine(); 
p.checkoutProcess.BeginErrorReadLine();