您如何从Windows服务读取控制台输出?

cas*_*ere 5 windows-services console-application c#-4.0

我有控制台应用程序ThirdPartyApplications.exe,必须从Windows服务运行。控制台应用程序给我带来了休息:确定,不确定和错误。

我需要在Windows服务中捕获这些响应。

我创建了功能

 using (var p = new System.Diagnostics.Process())
        {
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = @"C:\ThirdPartyApplications.exe";
            p.StartInfo.Arguments = "3";
            p.Start();
            string o = p.StandardOutput.ReadToEnd();

            p.WaitForExit();
        }
Run Code Online (Sandbox Code Playgroud)

如何捕获此输出?

编辑

 using (var p = new System.Diagnostics.Process())
        {
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = @"C:\ThirdPartyBatch.bat";
            p.StartInfo.Arguments = "file.zip -user.properties";
            p.Start();
            string o = p.StandardOutput.ReadToEnd();

            p.WaitForExit();
        }
Run Code Online (Sandbox Code Playgroud)

批处理文件为

@echo off
call run.bat %* 1>log\out.txt 2>log\err.txt
@echo code %ERRORLEVEL%
exit /B %ERRORLEVEL%
Run Code Online (Sandbox Code Playgroud)

在这里,在我的变量o中,我没有收到消息“代码10”

如果我有

@ECHO off
ECHO Hello
PAUSE
Run Code Online (Sandbox Code Playgroud)

在这里,我收到消息“你好”,但是如果我更改批处理文件

@ECHO off
call run.bat %* 1>log\out.txt 2>log\err.txt
ECHO Hello
PAUSE
Run Code Online (Sandbox Code Playgroud)

我没有收到消息“你好”

有什么帮助吗?

Ric*_*ard 3

我怎样才能捕获这个输出?

仅当不作为服务运行时。

Windows 上的可执行文件必须调用特定的 API(直接作为 Win32 应用程序或间接在 .NET 等框架下),如果它不调用这些 API(例如基于命令行开关1 的逻辑),则它是正常的可执行文件。

当作为服务运行时,可执行文件由服务控制管理器 (SCM) 启动,并且无法访问标准输出、错误或输入。


1这在开发和调试服务时非常有用:“交互”模式允许从命令行或在调试器中轻松运行。