通过命令提示符“C#”安装和卸载Windows服务

时间:2011-02-09 10:43:19

标签: 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();

2 个答案:

答案 0 :(得分:3)

您无需启动命令提示符。 您必须启动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);

答案 1 :(得分:0)

.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();
    }
相关问题