Call Command Prompt and Leave Window Open

13,277

This line;

procStartInfo.RedirectStandardOutput = true;

Is what's causing the window to close. Remove this line, or add a handler to the Process.StandardOutput to read the contents somewhere else;

string t = proc.StandardOutput.ReadToEnd();
Share:
13,277
Stubbs
Author by

Stubbs

Updated on June 13, 2022

Comments

  • Stubbs
    Stubbs almost 2 years

    I'm trying to call an ant script from a C# application. I want the console window to pop up and stay up (I'm just calling the command prompt now, but I eventually want to call an ant script, which can take up to an hour). This is the code that I'm using, which I altered from the 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);
        }
    }
    

    I also want to pass in up to 5 parameters, but right now I'm just concerned with keeping the window open long enough to see what's happening, and I'm not interested in reading any content that's generated by the ant script. I don't want to ask anyone to do my work for me, but I've been banging my head on this one for a while, so any help would be greatly appreciated!