Search This Blog

Friday, April 5, 2013

C# Code To Execute a Command line Dos Exe and display the result


Some times we may need to execute a another command line executable file and display its result as string.
You can use the following code snippet for that.


public static string ReadOutputFromCmdExection(string strFileName, string strParameter)
{
    string StrResult = "";
    ProcessStartInfo start = new ProcessStartInfo();
    start.FileName = strFileName; // Specify Executable Name.
    start.UseShellExecute = false;
    start.Arguments = strParameter;
    start.RedirectStandardOutput = true;

    using (Process process = Process.Start(start))
    {
        //
        // Read in all the text from the process with the StreamReader.
        //
        using (StreamReader reader = process.StandardOutput)
        {
            StrResult = reader.ReadToEnd();
        }
    }
    return StrResult;
}
Usage:
 string strTxt = ReadOutputFromCmdExection(@"c:\windows\system32\ipconfig.exe","" );

Console.WriteLine(strTxt);





This helps to get the out put as string, so that we can parse it and use as we require.

No comments:

Post a Comment