title: c# Run multiple commands in cmd.exe simultaneously and write the output to a text file
body: <p>Requirement :</p>
  
  <p>Run multiple commands in cmd.exe simultaneously and write the output to a single text file using c# including the start time and end time of the executed command </p>
  
  <p>Do note that I want to use dot net version 2.0 because this code needs to run on legacy OS like XP . Parallel and ConcurrentBag feature is under .net 4.5 version</p>
  
  <p>Code Summary :</p>
  
  <ol>
  <li>Created a string list which holds all the commands to be executed.</li>
  <li><p>Iterate through the string list and pass the command as a parameter to a class which has a static method runCommand(string command)</p></li>
  <li><p>using thread to make sure each command is executed in a separate thread in parallel.</p></li>
  </ol>
  
  <p>Problem :</p>
  
  <p>The code runs fine but the output gets mixed up with returns from all the commands when writing to console and i am sure the same problem would arise when writing to file ! How do i ensure that all the commands run in parallel + output looks neat and not mixed up .  Also note that when i try to write to a file it errors out because multiple processes are trying to write to the same file. </p>
  
  <p>Main </p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Diagnostics;
  using System.IO;
  using System.Text;
  using System.Threading;
  using BaileySoft.Utility;
  
  namespace Diagnostic_Commands
  {
      class Program
      {
          static void Main(string[] args)
          {
  
              // Log file creation
              string strDestopPath = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
              strDestopPath += "\\Diagnostic_Today.txt";
              StreamWriter w = File.AppendText(strDestopPath);
  
              List&lt;String&gt; commands = new List&lt;String&gt;();
              commands.Add("nslookup www.google.com");
              commands.Add("Tracert -d  www.apple.com");         
              commands.Add("ipconfig /all");
              commands.Add("ping www.google.com -n 10");       
              commands.Add("nslookup www.apple.com");
  
  
              foreach (string cmd in commands)
              {
  
  
                      Thread tReturn = new Thread(() =&gt; { Test_Con.runCommand(cmd); });
                      tReturn.IsBackground = true;
                      tReturn.Priority = ThreadPriority.AboveNormal;
                      tReturn.IsBackground = true;
                      tReturn.Start();
  
              }
  
              Console.ReadLine();
  
  
          }
  
      }
  }
  </code></pre>
  
  <p>Class</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Diagnostics;
  using System.Linq;
  using System.Text;
  using System.IO;
  using System.Threading;
  
  public static class Test_Con
  {
      static string d = null;
  
      public static void runCommand(string command)
      {
          string starttime;
          string endtime;
  
          //* Create your Process
          Process process = new Process();
          process.StartInfo.FileName = "cmd.exe";
          process.StartInfo.Arguments = "/c" + command;
  
          starttime = "Started at " + DateTime.Now + "\n";
  
          process.StartInfo.UseShellExecute = false;
          process.StartInfo.RedirectStandardOutput = true;
          process.StartInfo.RedirectStandardError = true;
          //* Set your output and error (asynchronous) handlers
          process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
          process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
          //* Start process and handlers
          process.Start();
          process.BeginOutputReadLine();
          process.BeginErrorReadLine();
  
          process.WaitForExit();
          endtime = "Completed at " + DateTime.Now + "\n";
  
          d+= "========================================================================";
          d+= starttime + endtime ;
  
          Console.WriteLine(d);
      }
      static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
      {
          //* Do your stuff with the output (write to console/log/StringBuilder)
          Console.WriteLine(outLine.Data); //This will keep writing all the command output irrespective    
  
      }
  
      }
  
  }
  </code></pre>