4

I am trying to create a Windows Forms C# project that interacts with the command prompt shell (cmd.exe).

I want to open a command prompt, send a command (like ipconfig) and then read the results back into the windows form into a string, textbox, or whatever.

Here is what I have so far, but I am stuck. I cannot write or read to the command prompt.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;


namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/k dir *.*";
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;

            p.Start();

            StreamWriter inputWriter = p.StandardInput;
            StreamReader outputWriter = p.StandardOutput;
            StreamReader errorReader = p.StandardError;
            p.WaitForExit();

        }
    }
}

Any help would be greatly appreciated.

Thanks.

slugster
  • 49,403
  • 14
  • 95
  • 145
surfline
  • 41
  • 1
  • 1
  • 2

2 Answers2

1

Here is a SO question that will give you the information you need:

How To: Execute command line in C#, get STD OUT results

Basically, you ReadToEnd on your System.IO.StreamReader.

So, for example, in your code you would modify the line StreamReader errorReader = p.StandardError; to read

using(StreamReader errorReader = p.StandardError)
{
   error = myError.ReadToEnd();
}
Community
  • 1
  • 1
IAmTimCorey
  • 16,412
  • 5
  • 39
  • 75
0
  var yourcommand = "<put your command here>";

  var procStart = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + yourcommand);
  procStart.CreateNoWindow = true;
  procStart.RedirectStandardOutput = true;
   procStart.UseShellExecute = false;

   var proc = new System.Diagnostics.Process();
   proc.StartInfo = procStart;
   proc.Start();
   var result = proc.StandardOutput.ReadToEnd();

   Console.WriteLine(result);
S P
  • 4,615
  • 2
  • 18
  • 31