【发布时间】:2011-08-25 08:16:10
【问题描述】:
我正在尝试在 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 上启动 Tomcat 作为使用 C# 的服务。好吧,我这样做是因为由于各种原因我无法使用 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)
啊!我感到很生气!
【问题讨论】:
-
我认为您需要
UseShellExecute = true才能使其工作。 -
更新了如果我尝试这个会发生什么。谢谢。
-
其实我更新了startup.bat,所以它不需要环境变量。还是什么都没有... :(
-
真的需要stdio重定向吗?
-
我的意思是在将 UseShellExecute 设置为 true 后,我将 RedirectStandardOutput 设置为 false。我还接受了一些老问题的答案……现在更好了吗?
标签: c# windows windows-services batch-file