使用C#代碼安裝 Windows 服務(不使用InstallUtil) (轉帖)

 轉自大豆男生

 

using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Configuration.Install;

static class Program
{
    
/// <summary>
    
/// 應用程序的主入口點。
    
/// </summary>
    [STAThread]
    
static void Main(string[] args)
    {
        
// 運行服務
        if (args.Length == 0)
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun 
= new ServiceBase[] { new MyService1() };
            ServiceBase.Run(ServicesToRun);
        }
        
// 安裝服務
        else if (args[0].ToLower() == "/i" || args[0].ToLower() == "-i")
        {
            
try
            {
                
string[] cmdline = { };
                
string serviceFileName = System.Reflection.Assembly.GetExecutingAssembly().Location;

                TransactedInstaller transactedInstaller 
= new TransactedInstaller();
                AssemblyInstaller assemblyInstaller 
= new AssemblyInstaller(serviceFileName, cmdline);
                transactedInstaller.Installers.Add(assemblyInstaller);
                transactedInstaller.Install(
new System.Collections.Hashtable());
            }
            
catch (Exception ex)
            {
                
string msg = ex.Message;
            }
        }
        
// 刪除服務
        else if (args[0].ToLower() == "/u" || args[0].ToLower() == "-u")
        {
            
try
            {
                
string[] cmdline = { };
                
string serviceFileName = System.Reflection.Assembly.GetExecutingAssembly().Location;

                TransactedInstaller transactedInstaller 
= new TransactedInstaller();
                AssemblyInstaller assemblyInstaller 
= new AssemblyInstaller(serviceFileName, cmdline);
                transactedInstaller.Installers.Add(assemblyInstaller);
                transactedInstaller.Uninstall(
null);
            }
            
catch (Exception ex)
            {
                
string msg = ex.Message;
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章