Run and Fetch cmd command prompt output using C#
In this article, i had explained about how to get the command prompt output without manually running command prompt. By using process, StreamReader, StreamWriter we can get the output of the command prompt in C#
Full Source code as follows
public partial class Form1 : Form
private void Form1_Load(object sender, EventArgs e)
//declaring the commandlinestring as dir
string commandlinestring = "dir";
//declaring process as p
Process p = new Process();
//creating object sw of streamwriter
//creating object sr of StreamReader
//creating object err of StreamReader
//declaring processstartinfo as psI and passing cmd text.
ProcessStartInfo psI = new ProcessStartInfo("cmd");
//setting UseShellExecute of the process to false enables you to redirect input, output, and error streams.
psI.UseShellExecute = false;
//setting true value indicating that the input for an application is read from the Process.StandardInput stream.
psI.RedirectStandardInput = true;
//setting true value of RedirectStandardOutput indicates the output of an application is written to the Process.StandardOutput stream.
psI.RedirectStandardOutput = true;
//setting ture value of RedirectStandardError indicates the error output of an application is written to the Process.StandardError stream.
psI.RedirectStandardError = true;
//setting true value to CreateNoWindow indicating whether to start the process in a new window.
psI.CreateNoWindow = true;
//StartInfo specifies a set of values that are used when you start a process.Specifies a set of values that are used when you start a process.
p.StartInfo = psI;
//Starts a process resource and associates it with a Process component.
//assigning process standardinput to sw
sw = p.StandardInput;
//assigning process StandardOutput to sr
sr = p.StandardOutput;
//assigning process StandardError to err
err = p.StandardError;
sw.AutoFlush = true;
//checking for the condition that the commandlinestring is not empty string then writes the commandlinestring
if (commandlinestring != "")
//execute default command
//binding the full input data to richtextbox
richTextBox1.Text = sr.ReadToEnd();
//binding the full output data to richtextbox
richTextBox1.Text += err.ReadToEnd();
I had attached sourcecode in zip format for reference.
No responses found. Be the first to comment...