Friday, June 13, 2014

C# run DOS command prompt

 Util myUtil = new Util();
         myUtil.ExecTask("ping", "10.99.10.101");
         string sOut = myUtil.SOutput.ToString();
         string sErr = myUtil.SErrOutput.ToString();  


   public class Util
   {
      StringBuilder m_sOutput;

      public StringBuilder SOutput
      {
         get { return m_sOutput; }
         set { m_sOutput = value; }
      }
      StringBuilder m_sErrOutput;

      public StringBuilder SErrOutput
      {
         get { return m_sErrOutput; }
         set { m_sErrOutput = value; }
      }
      Process mProcess;

      public void ExecTask(string sCmd, string sArgs)
      {
         m_sOutput = new StringBuilder();
         m_sErrOutput = new StringBuilder();
         // Setup the process start info
         var processStartInfo = new ProcessStartInfo(sCmd, sArgs)
         {
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true
         };

         // Setup the process
         mProcess = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true };

         // Register event
         mProcess.OutputDataReceived += OnOutputDataReceived;
         mProcess.ErrorDataReceived += OnErrorDataReceived;

         // Start process
         mProcess.Start();
         mProcess.BeginOutputReadLine();
         mProcess.BeginErrorReadLine();
         mProcess.WaitForExit();
      }

      void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
      {
         m_sOutput.AppendLine(e.Data);
      }

      void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
      {
         m_sErrOutput.AppendLine(e.Data);
      }
   }

No comments:

Post a Comment