Reputation: 47
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
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);
}
Upvotes: 2
Views: 4800
Reputation: 14024
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);
}
Upvotes: 6