C#ProcessStartInfo始终运行重复的进程

vie*_*n09 0 c#

我有一些代码打开cmd并运行命令然后获取输出,但它总是运行两次,有时输出丢失.

在此输入图像描述

这是我的代码,我多次重新检查,但无法弄清楚是什么原因.

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

任何的想法?

ror*_*.ap 5

因为你打了Process.Start()两次电话.在这里创建实例时process:

Process process = Process.Start(startInfo);
Run Code Online (Sandbox Code Playgroud)

再次在这里,靠近构造函数的底部:

process.Start(); 
Run Code Online (Sandbox Code Playgroud)