[英]Install and uninstall windows service via command prompt “C#”
我想通过命令提示符“ C#”安装和卸载win服务
以下代码不起作用,请帮助我
string strInstallUtilPath ="C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\";
string strInstallService = " InstallUtil.exe \"D:\\TestUser\\ServiceForPatch\\TestService\\bin\\Debug\\TestService.exe\"";
ProcessStartInfo PSI = new ProcessStartInfo("cmd.exe");
PSI.RedirectStandardInput = true;
PSI.RedirectStandardOutput = true;
PSI.RedirectStandardError = true;
PSI.UseShellExecute = false;
Process p = Process.Start(PSI);
System.IO.StreamWriter SW = p.StandardInput;
System.IO.StreamReader SR = p.StandardOutput;
SW.WriteLine(@"cd\");
SW.WriteLine(@"cd " + strInstallUtilPath);
SW.WriteLine(strInstallService);
p.WaitForExit();
SW.Close();
您无需启动命令提示符。 您必须启动InstallUtil并传递适当的参数。
修改了代码段,使用选项调用installutil,并将输出写入字符串,然后写入控制台窗口。
string strInstallUtilPath = @"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\installutil.exe";
string strInstallService = @"D:\TestUser\ServiceForPatch\TestService\bin\Debug\TestService.exe";
ProcessStartInfo processStartInfo =
new ProcessStartInfo(strInstallUtilPath, String.Format("/i {0}", strInstallService));
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.UseShellExecute = false;
Process process = new Process();
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit();
String output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
.NET Framework的内置ServiceInstaller对我而言无法正常工作,因此这是卸载Windows服务时要做的事情:
private void UninstallExistingService()
{
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
process.StartInfo = startInfo;
process.Start();
using (var sw = process.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("{0} {1}", "net stop", _serviceName);
sw.WriteLine("{0} {1}", "sc delete", _serviceName);
}
}
process.WaitForExit();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.