gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:49:21 25 4
gpt4 key购买 nike

我正在尝试在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com