使用C#代码安装、启动、停止、卸载Windows service(不使用InstallUtil.exe)


ContractedBlock.gif ExpandedBlockStart.gif Code
using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Configuration.Install;
using System.Collections;

namespace AutoUpdate
{
    
public class InstalUtil
    {
        
public static void InstallService(string filepath, string serviceName, string[] options)
        {
            
try
            {
                
if (!IsServiceExisted(serviceName))
                {
                    IDictionary mySavedState 
= new Hashtable();
                    AssemblyInstaller myAssemblyInstaller 
= new AssemblyInstaller();                    
                    myAssemblyInstaller.UseNewContext 
= true;
                    myAssemblyInstaller.Path 
= filepath;
                    myAssemblyInstaller.CommandLine 
= options;
                    myAssemblyInstaller.Install(mySavedState);
                    myAssemblyInstaller.Commit(mySavedState);
                    myAssemblyInstaller.Dispose();
                }
            }
            
catch (Exception ex)
            {
                
throw new Exception("Install Service Error\n" + ex.Message);
            }
        }

        
public static void UnInstallService(string filepath, string serviceName, string[] options)
        {
            
try
            {
                
if (IsServiceExisted(serviceName))
                {
                    AssemblyInstaller myAssemblyInstaller 
= new AssemblyInstaller();
                    myAssemblyInstaller.UseNewContext 
= true;
                    myAssemblyInstaller.Path 
= filepath;
                    myAssemblyInstaller.CommandLine 
= options;
                    myAssemblyInstaller.Uninstall(
null);
                    myAssemblyInstaller.Dispose();
                }
            }
            
catch (Exception ex)
            {
                
throw new Exception("UnInstall Service Error\n" + ex.Message);
            }
        }

        
public static bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services 
= ServiceController.GetServices();
            
foreach (ServiceController s in services)
            {
                
if (s.ServiceName == serviceName)
                {
                    
return true;
                }
            }
            
return false;
        }

        
public static void StartService(string serviceName)
        {
            
if (IsServiceExisted(serviceName))
            {
                System.ServiceProcess.ServiceController service 
= new System.ServiceProcess.ServiceController(serviceName);
                
if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running &&
                    service.Status 
!= System.ServiceProcess.ServiceControllerStatus.StartPending)
                {
                    service.Start();
                    
for (int i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(
1000);
                        
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                        {
                            
break;
                        }
                        
if (i == 59)
                        {
                            
throw new Exception("Start Service Error\n" + serviceName);
                        }
                    }
                }
            }
        }

        
public static void StopService(string serviceName)
        {
            
if (IsServiceExisted(serviceName))
            {
                System.ServiceProcess.ServiceController service 
= new System.ServiceProcess.ServiceController(serviceName);
                
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    service.Stop();
                    
for (int i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(
1000);
                        
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
                        {
                            
break;
                        }
                        
if (i == 59)
                        {
                            
throw new Exception("Stop Service Error\n" + serviceName);
                        }
                    }
                }
            }
        }
    }
}

 

 

在调用 myAssemblyInstaller.Install(mySavedState);或myAssemblyInstaller.Uninstall(null);之后,该程序文件就不能被删除了,直到安装程序推出,而我想在卸载后立即更新程序文件,可是因为不能删除,也就替换不了了。那位知道解决方法?不妨回帖:)

 

 

 

通过.net reflector查看installutil.exe的源代码如下:

 

ContractedBlock.gif ExpandedBlockStart.gif Code
public static int Main(string[] args)
{
    Thread.CurrentThread.CurrentUICulture 
= CultureInfo.CurrentUICulture.GetConsoleFallbackUICulture();
    
if (((Console.OutputEncoding.CodePage != 0xfde9&& (Console.OutputEncoding.CodePage != Thread.CurrentThread.CurrentUICulture.TextInfo.OEMCodePage)) && (Console.OutputEncoding.CodePage != Thread.CurrentThread.CurrentUICulture.TextInfo.ANSICodePage))
    {
        Thread.CurrentThread.CurrentUICulture 
= new CultureInfo("en-US");
    }
    Assembly.GetEntryAssembly().GetCustomAttributes(
typeof(AssemblyProductAttribute), true);
    Console.WriteLine(Res.GetString(
"InstallUtilSignOnMessage"new object[] { "2.0.50727.1433", CommonResStrings.CopyrightForCmdLine }));
    
try
    {
        ManagedInstallerClass.InstallHelper(args);
    }
    
catch (Exception exception)
    {
        Console.WriteLine(exception.Message);
        
return -1;
    }
    
return 0;
}


 

ManagedInstallerClass.InstallHelper()代码:

 

 

ContractedBlock.gif ExpandedBlockStart.gif Code
public static void InstallHelper(string[] args)
{
    
bool flag = false;
    
bool flag2 = false;
    TransactedInstaller installerWithHelp 
= new TransactedInstaller();
    
bool flag3 = false;
    
try
    {
        ArrayList list 
= new ArrayList();
        
for (int i = 0; i < args.Length; i++)
        {
            
if (args[i].StartsWith("/", StringComparison.Ordinal) || args[i].StartsWith("-", StringComparison.Ordinal))
            {
                
string strA = args[i].Substring(1);
                
if ((string.Compare(strA, "u", StringComparison.OrdinalIgnoreCase) == 0|| (string.Compare(strA, "uninstall", StringComparison.OrdinalIgnoreCase) == 0))
                {
                    flag 
= true;
                }
                
else if ((string.Compare(strA, "?", StringComparison.OrdinalIgnoreCase) == 0|| (string.Compare(strA, "help", StringComparison.OrdinalIgnoreCase) == 0))
                {
                    flag3 
= true;
                }
                
else if (string.Compare(strA, "AssemblyName", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    flag2 
= true;
                }
                
else
                {
                    list.Add(args[i]);
                }
            }
            
else
            {
                Assembly assembly 
= null;
                
try
                {
                    
if (flag2)
                    {
                        assembly 
= Assembly.Load(args[i]);
                    }
                    
else
                    {
                        assembly 
= Assembly.LoadFrom(args[i]);
                    }
                }
                
catch (Exception exception)
                {
                    
if (args[i].IndexOf('='!= -1)
                    {
                        
throw new ArgumentException(Res.GetString("InstallFileDoesntExistCommandLine"new object[] { args[i] }), exception);
                    }
                    
throw;
                }
                AssemblyInstaller installer2 
= new AssemblyInstaller(assembly, (string[]) list.ToArray(typeof(string)));
                installerWithHelp.Installers.Add(installer2);
            }
        }
        
if (flag3 || (installerWithHelp.Installers.Count == 0))
        {
            flag3 
= true;
            installerWithHelp.Installers.Add(
new AssemblyInstaller());
            
throw new InvalidOperationException(GetHelp(installerWithHelp));
        }
        installerWithHelp.Context 
= new InstallContext("InstallUtil.InstallLog", (string[]) list.ToArray(typeof(string)));
    }
    
catch (Exception exception2)
    {
        
if (flag3)
        {
            
throw exception2;
        }
        
throw new InvalidOperationException(Res.GetString("InstallInitializeException"new object[] { exception2.GetType().FullName, exception2.Message }));
    }
    
try
    {
        
string str2 = installerWithHelp.Context.Parameters["installtype"];
        
if ((str2 != null&& (string.Compare(str2, "notransaction", StringComparison.OrdinalIgnoreCase) == 0))
        {
            
string str3 = installerWithHelp.Context.Parameters["action"];
            
if ((str3 != null&& (string.Compare(str3, "rollback", StringComparison.OrdinalIgnoreCase) == 0))
            {
                installerWithHelp.Context.LogMessage(Res.GetString(
"InstallRollbackNtRun"));
                
for (int j = 0; j < installerWithHelp.Installers.Count; j++)
                {
                    installerWithHelp.Installers[j].Rollback(
null);
                }
            }
            
else if ((str3 != null&& (string.Compare(str3, "commit", StringComparison.OrdinalIgnoreCase) == 0))
            {
                installerWithHelp.Context.LogMessage(Res.GetString(
"InstallCommitNtRun"));
                
for (int k = 0; k < installerWithHelp.Installers.Count; k++)
                {
                    installerWithHelp.Installers[k].Commit(
null);
                }
            }
            
else if ((str3 != null&& (string.Compare(str3, "uninstall", StringComparison.OrdinalIgnoreCase) == 0))
            {
                installerWithHelp.Context.LogMessage(Res.GetString(
"InstallUninstallNtRun"));
                
for (int m = 0; m < installerWithHelp.Installers.Count; m++)
                {
                    installerWithHelp.Installers[m].Uninstall(
null);
                }
            }
            
else
            {
                installerWithHelp.Context.LogMessage(Res.GetString(
"InstallInstallNtRun"));
                
for (int n = 0; n < installerWithHelp.Installers.Count; n++)
                {
                    installerWithHelp.Installers[n].Install(
null);
                }
            }
        }
        
else if (!flag)
        {
            IDictionary stateSaver 
= new Hashtable();
            installerWithHelp.Install(stateSaver);
        }
        
else
        {
            installerWithHelp.Uninstall(
null);
        }
    }
    
catch (Exception exception3)
    {
        
throw exception3;
    }
}

 


 实际上installutil.exe也是利用TransactedInstaller、AssemblyInstaller等类实现的。

 

 

 

 

 

 

 


转载于:https://www.cnblogs.com/h2appy/archive/2008/09/01/1281059.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值