c# - 如何在 C# 的 Windows 服务中执行批处理脚本?

标签 c# windows windows-services batch-file

我正在尝试在 C# Windows 服务中执行 .bat 脚本,但它似乎无法正常工作。

所以我尝试执行的脚本 startup.bat 依次调用另一个脚本 call catalina.bat ...,后者依次执行 启动java ...

我可以手动执行 startup.bat,但我想将其作为 Windows 服务运行。当我尝试在 C# Windows 服务应用程序中执行此操作时,似乎什么也没有发生。我的 Windows 服务代码如下所示:

public class MyService : ServiceBase
{
    public static void Main(string[] args)
    {
        ServiceBase.Run(new MyService());
    }

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        this.RunScript(@"bin\startup.bat");
        Thread.Sleep(1000);
    }

    protected override void OnStop()
    {
        base.OnStop();
        this.RunScript(@"bin\shutdown.bat");
        Thread.Sleep(1000);
    }

    private void RunScript(string processFileName)
    {
        var startInfo = new ProcessStartInfo
        {
            FileName = "cmd.exe",
            Arguments = "/C " + Path.Combine(@"C:\server", processFileName),
            CreateNoWindow = true,
            ErrorDialog = false,
            RedirectStandardError = true,
            RedirectStandardOutput = true,
            UseShellExecute = false,
            WindowStyle = ProcessWindowStyle.Hidden
        };

        startInfo.EnvironmentVariables.Add("CATALINA_HOME", @"c:\server");

        var process = new Process();
        process.StartInfo = startInfo;
        process.Start();
    }
}

我不明白为什么这不执行。我做错了什么?

是的,您可能会注意到我正在尝试使用 C# 在 Windows 上将 Tomcat 作为服务启动。好吧,我这样做是因为出于各种原因我无法使用 tomcat7.exe,但最好不要问我为什么要这样做。不管是什么原因,我在这里所做的也应该有效,不是吗?

根据 Gabe 的建议更新:

如果我设置 UseShellExecute = true 我得到一个异常:

System.InvalidOperationException: The Process object must have the UseShellExecute property set to false in order to redirect IO streams.
    at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
    at System.Diagnostics.Process.Start()
    at MyService.RunScript(String processFileName)

所以我将 RedirectStandardError 和 RedirectStandardOutput 设置为 false,这会产生此错误:

System.InvalidOperationException: The Process object must have the UseShellExecute property set to false in order to use environment variables.
  at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
  at System.Diagnostics.Process.Start()
  at MyService.RunScript(String processFileName)

哎呀!我感到很生气!

最佳答案

运行“cmd.exe”并将“startup.bat”作为参数传递。

关于c# - 如何在 C# 的 Windows 服务中执行批处理脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5999169/

相关文章:

c# - 如何从文件属性中获取详细信息?

c# - 在窗口服务中检测关闭

java - 如何制作自定义 Windows 服务?

c# - 求解 WAV 文件中的振幅和频率

c# - WCF 安全支持提供程序接口(interface) (SSPI) 协商失败

windows - 我在哪里可以下载 Subversion 二进制文件?

windows - 在 Win32 应用程序中使用 Windows 窗体

JavaExe 和 Java 应用程序作为 Windows 系统服务与桌面交互

c# - 如何通过调用带字符串参数的 WiX 自定义操作的 Installshield 创建自定义操作?

c# - 通过针对接口(interface)编程来保留数据