[英]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.