用C# 2005 写了个简单的windows服务 
注册必须要自己手动的执行 installutil 注册安装服务高分求教 如何在程序里实现windows服务的自动注册?
(做了个安装包,安装时提示无法从命令行或调试器启动服务,必须首先安装windows服务,使用installtil.exe)

解决方案 »

  1.   

    static void Main(string[] args)
            {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                if (args.Length > 0)
                {
                    AssemblyInstaller myAssemblyInstaller;
                    myAssemblyInstaller = new AssemblyInstaller();
                    myAssemblyInstaller.UseNewContext = true;
                    myAssemblyInstaller.Path = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + System.AppDomain.CurrentDomain.FriendlyName;
                    Hashtable mySavedState = new Hashtable();
                    switch (args[0].ToLower())
                    {
                        case "-i":
                            myAssemblyInstaller.Install(mySavedState);
                            myAssemblyInstaller.Commit(mySavedState);
                            myAssemblyInstaller.Dispose();
                            return;
                        case "-u":
                            myAssemblyInstaller.CommandLine = new string[1] { "/u" };
                            myAssemblyInstaller.Uninstall(null);
                            myAssemblyInstaller.Dispose();
                            return;
                        default: 
                            System.Console.WriteLine("-i 安装服务!");
                            System.Console.WriteLine("-u 卸载服务!");
                            System.Console.ReadKey();
                            return;                }
                }
                else
                {
                    try
                    {
                        ServiceBase ServicesToRun = new QYTService();
                        ServiceBase.Run(ServicesToRun);
                    }
                    catch (Exception ex)
                    {
                        LogEvent.Error("发现未处理异常!", string.Format("异常消息:\n{0}", ex.ToString()));
                    }
                }
            }你看看这段代码就知道了!
      

  2.   

    AssemblyInstaller myAssemblyInstaller;
    myAssemblyInstaller = new AssemblyInstaller();
    myAssemblyInstaller.UseNewContext = true;
    myAssemblyInstaller.Path = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + System.AppDomain.CurrentDomain.FriendlyName;//这是你要安装的服务程序的路径名。
    Hashtable mySavedState = new Hashtable();
    myAssemblyInstaller.Install(mySavedState);//开始安装。
    myAssemblyInstaller.Commit(mySavedState);//提交安装。
    myAssemblyInstaller.Dispose();
      

  3.   

    1. 服务程序的开发环境中有个“添加安装程序”的链接,点击即可使用.net自带的安装程序,你只需设置一些参数即可。
    2. 有特殊需要的,使用API函数,DLLIMPORT导入包装,虽然代码很长,但是实用。
      

  4.   

    to楼上的。已经做了安装程序,在安装的时候提示:安装时提示无法从命令行或调试器启动服务,必须首先安装windows服务,使用installtil.exe)不知道怎么设置参数?