[英]How can I execute a batch script in a windows service in C#?
我正在尝试在C#Windows服务中执行.bat脚本,但似乎无法正常工作。
因此,我尝试执行的脚本startup.bat
依次调用另一个脚本, call catalina.bat ...
,该脚本依次执行start 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();
}
}
我不明白为什么这个不执行。 我究竟做错了什么?
是的,您可能会注意到我正在尝试在Windows上使用C#将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”作为参数。
为了解决这个问题,问题确实是Windows安全权限问题。
提出的建议在这里似乎解决我的问题。
尝试在服务设置中设置“允许服务与桌面交互”。
尝试:
FileName = "%comspec%",
Arguments = "/C " + Path.Combine(@"C:\server", processFileName),
如果您的脚本可以作为交互式用户运行,但不能作为服务运行,则可能有两个明显的原因:
这些建议本质上是猜测,但由于信息很少,因此很难做得更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.