2016-07-08 3 views
1

요구를 텍스트 파일로 출력을 쓰기 : cmd.exe를에C#을 실행 여러 cmd.exe를의 명령 동시에

실행 여러 개의 명령을 동시에 시작 시간을 포함하여 C# .NET을 사용하여 하나의 텍스트 파일로 출력을 작성하고 실행 된 명령의 종료 시간

이 코드는 XP와 같은 레거시 OS에서 실행해야하므로 dot net 버전 2.0을 사용하려고합니다. 병렬 및 ConcurrentBag 기능은 .NET 4.5 버전을 받고있다

코드 요약 :

  1. 모든 명령이 실행되도록 유지하는 문자열 목록을 만들었습니다.
  2. 캐릭터 목록을 반복하고 정적 메소드 runCommand (문자열 명령) 반드시 각 명령이 병렬로 별도의 쓰레드로 실행하기 위해 스레드를 사용

  3. 을 갖는 클래스 매개 변수로 명령을 전달한다.

문제 :

코드는 잘 실행하지만 출력이 콘솔에 쓰는 모든 명령의 반환과 함께 혼합 도착하고 난 파일에 기록 할 때 같은 문제가 발생할 것이라고 확신합니다! 병렬 + 출력에서 ​​실행되는 모든 명령이 깔끔하게 보이고 섞이지 않도록하는 방법은 무엇입니까? 또한 여러 파일이 같은 파일에 쓰려고하기 때문에 파일에 쓰려고 할 때 오류가 발생합니다.

당신은 병렬 및 ConcurrentBag 작업 할 수

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  

    } 

    } 

} 
+1

더 나은 당신이 할 수있는 그런 다음에 출력을 추가하고 모든 명령이 완료되면 파일에 사전 내용을 작성, 수집의 몇 가지 유형 (PID 및 문자열의 예에 따라 사전)를 가지고있다. – Gusman

+1

http://stackoverflow.com/a/8055430/366904 –

+0

http://stackoverflow.com/questions/8035029/how-to-write-in-a-single-file-with-multiple-threads –

답변

1

홈페이지

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<String> commands = new List<String>(); 
      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(() => { Test_Con.runCommand(cmd); }); 
        tReturn.IsBackground = true; 
        tReturn.Priority = ThreadPriority.AboveNormal; 
        tReturn.IsBackground = true; 
        tReturn.Start(); 

      } 

      Console.ReadLine(); 


     } 

    } 
} 

클래스입니다. 벨로우 (Bellow)를 예로들 수 있지만 개선해야합니다.

static void Main(string[] args) 
     { 
      // Log file creation 
      var strDestopPath = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); 
      strDestopPath += "\\Diagnostic_Today.txt"; 
      var w = File.AppendText(strDestopPath); 

      var commands = new ConcurrentBag<string>(); 
      //List<String> commands = new List<String>(); 
      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"); 

      var results = new ConcurrentBag<Tuple<string, string>>(); 

      Parallel.ForEach(commands, cmd => { 
       new Test_Con(results).runCommand(cmd); 
      }); 


      //Your results are here: 
      foreach (var result in results) 
      { 
       Console.WriteLine("Command: {0}",result.Item1); 
       Console.WriteLine("OutPut: {0}",result.Item1); 
       Console.WriteLine("----------------------------"); 
      } 

      Console.ReadLine(); 
     } 
    } 

    public class Test_Con 
    { 
     static string d = null; 
     private ConcurrentBag<Tuple<string, string>> results; 
     private string command; 

     public Test_Con(ConcurrentBag<Tuple<string, string>> results) 
     { 
      this.results = results; 
     } 

     public void runCommand(string command) 
     { 
      this.command = 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); 
     } 
     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  

      results.Add(new Tuple<string, string>(command, outLine.Data)); 
     } 

    } 
+0

참고 사항 이 코드는 XP와 같은 레거시 OS에서 실행해야하기 때문에 닷넷 버전 2.0을 사용하고 싶습니다. Parallel 및 ConcurrentBag 기능은 .net 4.5 버전에 있습니다. – Cryptonology

관련 문제