C#批处理文件执行永不退出

C# batch file execution never exits

我正在尝试执行一个单独 运行 的批处理文件。我现在正尝试通过将其部署为 windows 服务来自动执行此操作,该服务侦听文件夹并使用文件观察程序事件调用批处理文件。这是代码 -

void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
    ServiceEventLog.WriteEntry(TheServiceName + " Inside fileSystemWatcher_Created() - ");
    if (e.Name.Trim().ToUpper().Contains("FU4DGF_TRADES"))
    {
        try
        {
            Utilities.SendEmail("IAMLDNSMTP", 25, "desmond.quilty@investecmail.com", "IAMITDevelopmentServices@investecmail.com", "Ben.Howard@investecmail.com", "prasad.matkar@investecmail.com", "StatPro BatchFile Execution Started ", "");
            int exitCode;
            //  ProcessStartInfo processInfo;
            ServiceEventLog.WriteEntry(TheServiceName + " Before creation of instance of Batch process - ");
            Process process = new Process();
            process.StartInfo.FileName = @"C:\Program Files (x86)\StatPro Suite\MonthlyUpload.bat";
            process.StartInfo.RedirectStandardOutput = false;
            process.StartInfo.RedirectStandardError = false;
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.WorkingDirectory = @"C:\Program Files (x86)\StatPro Suite";
            process.StartInfo.UseShellExecute = false;
            ServiceEventLog.WriteEntry(TheServiceName + " Before start  of Batch process - ");
            process.Start();
            ServiceEventLog.WriteEntry(TheServiceName + " After start  of Batch process - ");
            process.WaitForExit();
            //while (!process.HasExited)
            //{
            //    System.Threading.Thread.Sleep(100);
            //}

            ServiceEventLog.WriteEntry(TheServiceName + " After process.close - ");
            System.Environment.ExitCode = process.ExitCode;
        }

我可以从我的事件日志中看到它一直在记录 - 在批处理开始之前。大概在那之后,该过程通过调用 process.Start() 开始,但随后什么也没有发生。事件日志中没有任何内容,服务仍在 运行ning,即没有崩溃。没有错误。我可以从任务管理器中看到它确实调用了它应该通过批处理文件调用的 exe,但 exe 只是保留在内存中,内存不变,0 CPU 使用表明 exe 没有做任何事情。如果我 运行 手动批处理文件它工作正常。知道可能出了什么问题吗?

您已禁用 UseShellExecute。这意味着 您不能使用 shell 来执行文件 bat 个文件不是可执行文件,它们是 shell 个脚本。

既然您没有重定向标准 I/O,只需启用 UseShellExecute 就可以了。