调用命令提示符并保持窗口打开

7

我正在尝试从C#应用程序调用一个Ant脚本。我希望控制台窗口弹出并保持开启状态(现在只是调用命令提示符,但最终我想调用一个可能需要长达一小时的Ant脚本)。以下是我使用的代码,它改自原始代码:

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脚本生成的任何内容都不感兴趣。我不想要求任何人替我完成工作,但我已经困扰了一段时间,所以任何帮助将不胜感激!

1个回答

8

这行代码;

procStartInfo.RedirectStandardOutput = true;

导致窗口关闭的原因是什么。移除此行,或者添加一个处理程序到Process.StandardOutput来读取内容到其他位置;

string t = proc.StandardOutput.ReadToEnd();

好的!这个问题解决了!今天大部分时间我都很沮丧。有没有什么办法让它能够处理多条命令?尤其是像"cd c:\users\"这样带有空格的命令? - Stubbs
2
具有空格的命令应按原样正确解释。对于多个命令,您可能需要将命令发送到批处理文件中,或者查看将命令发送到标准输入流,我认为您不能只将所有命令作为一个字符串发送。 - RJ Lohan
你也可以像这样发送多个参数:链接。这将更改目录并向批处理文件传递4个参数。对某些人可能有帮助。 - Stubbs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接