2016-07-28 115 views
0

我有一些代碼來打開cmd並運行該命令,然後獲得輸出,但它總是運行兩次,有時輸出丟失。C#ProcessStartInfo始終運行重複進程

enter image description here

這裏是我的代碼,我重新檢查很多次,但找不出病因是什麼。

using System; 
using System.Diagnostics; 
using System.IO; 
using System.Security.Cryptography; 
using System.Security.Permissions; 
using System.Text; 
using System.Threading; 


namespace CommandHandler 
{ 
    class Program 
    { 
     public static string change_file = AppDomain.CurrentDomain.BaseDirectory + @"change\change.txt"; 
     public static void Main() 
     { 
      //Console.SetWindowSize(Console.LargestWindowWidth, Console.LargestWindowHeight); 
      Console.BackgroundColor = ConsoleColor.Black; 
      Console.ForegroundColor = ConsoleColor.Green; 

      //ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/c php d:/test.php") 
      ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/c D:\\php64\\php D:\\xampp\\htdocs\\xxx\\bin\\listen.php") 
      { 
       WindowStyle = ProcessWindowStyle.Hidden, 
       UseShellExecute = false, 
       RedirectStandardOutput = true, 
       CreateNoWindow = true 
      }; 

      Process process = Process.Start(startInfo); 
      //process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(proc_OutputDataReceived); 
      process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => 
      { 
       // Prepend line numbers to each line of the output. 
       if (!String.IsNullOrEmpty(e.Data)) 
       { 
        String value = e.Data.ToLower(); 
        Console.WriteLine(e.Data); 
        if (value.Contains("php fatal error:")) 
        { 
         string hash = md5(DateTime.Now.ToString()); 
         System.IO.File.WriteAllText(change_file, hash); 
        } 
       } 
      }); 
      process.BeginOutputReadLine(); 
      process.Start(); 
      process.WaitForExit(); 
      Console.ReadKey(); 
     } 

     public static byte[] encryptData(string data) 
     { 
      System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider(); 
      byte[] hashedBytes; 
      System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); 
      hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(data)); 
      return hashedBytes; 
     } 

     public static string md5(string data) 
     { 
      return BitConverter.ToString(encryptData(data)).Replace("-", "").ToLower(); 
     } 
    } 
} 

任何想法?

+1

也許是因爲你調用兩次的Process.Start()? – OrMiz

+1

老實說,我不確定你爲什麼得到了投票。不是出於任何正當的理由,那是。 –

+0

@ roryap我不在乎投票或投票。我只是想解決我的問題,我知道很多將他們的成績放在Stackoverflow上的人進入他們的簡歷,在我​​看來,這實在是浪費時間。但當我點擊投票給你時,我真的很享受。 – vietnguyen09

回答

5

因爲您要撥打Process.Start()兩次。在這裏,當你創建實例process

Process process = Process.Start(startInfo); 

,並再次在這裏,附近構造函數的底部:

process.Start();