2

I wrote a code for run cmd commands from c# form application. Now I want to get the output of the cmd to a lable in winform. I wrote a code. but it is giving me following error

Screenshot of the Error

An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll Additional information: StandardOut has not been redirected or the process hasn't started yet.

how to fix it? this is my original code.

private void button1_Click(object sender, EventArgs e)
{
    System.Diagnostics.Process process = new System.Diagnostics.Process();
    System.Diagnostics.ProcessStartInfo startiNFO = new  System.Diagnostics.ProcessStartInfo();

    startiNFO.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    startiNFO.FileName = "cmd.exe";
    startiNFO.Arguments = "/C ipconfig";
    startiNFO.UseShellExecute = false;

    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardInput = true;

    process.StartInfo = startiNFO;

    process.Start();

    string outp = process.StandardOutput.ReadToEnd();
    process.WaitForExit();

    MessageBox.Show(outp);
}  

1 Answer 1

6

instead of process.WaitForExit(); do something like this

The complete code for your function would look something like this

private void button1_Click(object sender, EventArgs e)
{
    System.Diagnostics.Process process = new System.Diagnostics.Process();
    process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/C ipconfig";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardInput = true;
    process.Start();
    string q = "";
    while(!process.HasExited)
    {
        q += process.StandardOutput.ReadToEnd();
    }
    label1.text = q;
    MessageBox.Show(q);
} 
12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.