2012-09-28 53 views
6

我试图从C#应用程序调用一个ant脚本。我想让控制台窗口弹出并保持(我现在只是调用命令提示符,但最终我想调用一个蚂蚁脚本,这可能需要一个小时)。这是我使用这是我从original改变了代码,:调用命令提示符并让窗口打开

public void ExecuteCommandSync(object command) 
{ 
    try 
    { 
     // create the ProcessStartInfo using "cmd" as the program to be run, 
     // and "/c " as the parameters. 
     // Incidentally, /c tells cmd that we want it to execute the command that follows, 
     // and then exit. 
     System.Diagnostics.ProcessStartInfo procStartInfo = 
     new System.Diagnostics.ProcessStartInfo("cmd", "/k " + command); 

     // The following commands are needed to redirect the standard output. 
     // This means that it will be redirected to the Process.StandardOutput StreamReader. 
     procStartInfo.RedirectStandardOutput = true; 
     procStartInfo.UseShellExecute = false; 
     // Do not create the black window. 
     procStartInfo.CreateNoWindow = false; 
     // Now we create a process, assign its ProcessStartInfo and start it 
     System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
     proc.StartInfo = procStartInfo; 

     proc.Start(); 
     proc.WaitForExit(); 

    } 
    catch (Exception objException) 
    { 
     Console.WriteLine(objException); 
    } 
} 

我也想通过多达5个参数,但现在我只是关心的是保持窗口打开足够长的时间看看发生了什么,并且我对阅读由ant脚本生成的任何内容不感兴趣。我不想要求任何人为我做我的工作,但我已经在这一段时间里抨击了我的头脑,所以任何帮助将不胜感激!

回答

7

这条线;

procStartInfo.RedirectStandardOutput = true; 

是什么导致窗口关闭。删除这一行,或者向Process.StandardOutput添加一个处理程序来读取其他地方的内容;

string t = proc.StandardOutput.ReadToEnd(); 
+0

工作!对于今天的大多数人都感到沮丧。任何想法如何让它与多个命令一起工作?特别是像下面这样的空白空间:cd c:\\ users \\ – Stubbs

+2

带空格的命令应该按原样正确解释。对于多个命令;您可能需要将命令发送到批处理文件,或者查看向StandardInputStream发送命令,我不认为您可以将它全部发送到一个字符串中。 –

+0

你也可以发送像这样的多个参数:[link](http://stackoverflow.com/questions/5591382/how-to-execute-multiple-cammand-in-command-prompt-using-c-sharp)。这会更改目录并将4个参数传递给批处理文件。可能对某人有帮助。 – Stubbs