我试图在C#windows服务中执行.bat脚本,但似乎没有工作。如何在C#中的Windows服务中执行批处理脚本?
所以我想执行,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上启动Tomcat作为C#服务。那么我这样做是因为我由于各种原因而无法使用tomcat7.exe,但最好不要问我为什么要做这样的事情。无论原因是什么,我在这里做的事情也应该起作用,不是吗?
响应Gabe的建议更新:
如果我设置UseShellExecute =真我得到一个异常:
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)
唉!我感到愤怒!
我认为你需要'UseShellExecute = true'才能工作。 – Gabe 2011-05-14 01:25:50
已更新,如果我尝试此操作会发生什么情况。谢谢。 – 2011-05-14 02:30:10
其实,我更新了startup.bat,所以它不需要环境变量。依然没有...:( – 2011-05-14 02:48:06