【问题标题】:Call Command Prompt and Leave Window Open调用命令提示符并保持窗口打开
【发布时间】:2012-09-28 00:16:15
【问题描述】:

我正在尝试从 C# 应用程序调用 ant 脚本。我希望控制台窗口弹出并保持不变(我现在只是调用命令提示符,但我最终想调用一个 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 脚本生成的任何内容不感兴趣.我不想让任何人为我做我的工作,但我一直在努力解决这个问题,所以任何帮助都将不胜感激!

【问题讨论】:

    标签: c# shell ant


    【解决方案1】:

    这一行;

    procStartInfo.RedirectStandardOutput = true;
    

    是什么导致窗口关闭。删除此行,或向 Process.StandardOutput 添加处理程序以在其他地方读取内容;

    string t = proc.StandardOutput.ReadToEnd();
    

    【讨论】:

    • 成功了!今天大部分时间都对此感到沮丧。知道如何让它与多个命令一起工作吗?尤其是带有空格的,例如: cd c:\\users\\
    • 带空格的命令应按原样正确解释。对于多个命令;您可能需要将命令发送到批处理文件,或者查看将命令发送到 StandardInputStream,我认为您不能将其全部发送到一个字符串中。
    • 您也可以像这样发送多个参数:link。这会更改目录并将 4 个参数传递给批处理文件。可能对某人有帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多