天天看點

C#操作注冊服務解除安裝服務啟動服務停止服務.. .

using system;

using system.configuration.install;

using system.collections;

using system.collections.specialized;

idictionary statesaver = new hashtable();

一、安裝服務:

private void installservice(idictionary statesaver, string filepath)

        {

            try

            {

                system.serviceprocess.servicecontroller service = new system.serviceprocess.servicecontroller("servicename");

                if(!serviceisexisted("servicename"))

                {

                    //install service

                    assemblyinstaller myassemblyinstaller = new assemblyinstaller();

                    myassemblyinstaller.usenewcontext = true;

                    myassemblyinstaller.path =filepath;

                    myassemblyinstaller.install(statesaver);

                    myassemblyinstaller.commit(statesaver);

                    myassemblyinstaller.dispose();

                    //--start service

                    service.start();

                }

                else

                    if (service.status != system.serviceprocess.servicecontrollerstatus.running && service.status != system.serviceprocess.servicecontrollerstatus.startpending)

                    {

                        service.start();

                    }

            }

            catch (exception ex)

                throw new exception("installserviceerror/n" + ex.message);

        }

或者

         /// <summary>

        /// 安裝服務

        /// </summary>

        /// <param name="p_path">指定服務檔案路徑</param>

        /// <param name="p_servicename">傳回安裝完成後的服務名</param>

        /// <returns>安裝資訊 正确安裝傳回""</returns>

        public static string insertservice(string p_path, ref string p_servicename)

            if (!file.exists(p_path)) return "檔案不存在!";

            p_servicename = "";

            fileinfo _insertfile = new fileinfo(p_path);

            idictionary _savedstate = new hashtable();

                //加載一個程式集,并運作其中的所有安裝程式。

                assemblyinstaller _assemblyinstaller = new assemblyinstaller(p_path, new string[] { "/logfile=" + _insertfile.directoryname + "//" + _insertfile.name.substring(0, _insertfile.name.length - _insertfile.extension.length) + ".log" });

                _assemblyinstaller.usenewcontext = true;

                _assemblyinstaller.install(_savedstate);

                _assemblyinstaller.commit(_savedstate);

                type[] _typelist = _assemblyinstaller.assembly.gettypes();//擷取安裝程式集類型集合

                for (int i = 0; i != _typelist.length; i++)

                    if (_typelist[i].basetype.fullname == "system.configuration.install.installer")

                        //找到system.configuration.install.installer 類型

                        object _insertobject = system.activator.createinstance(_typelist[i]);//建立類型實列

                        fieldinfo[] _fieldlist = _typelist[i].getfields(bindingflags.nonpublic | bindingflags.instance);

                        for (int z = 0; z != _fieldlist.length; z++)

                        {

                            if (_fieldlist[z].fieldtype.fullname == "system.serviceprocess.serviceinstaller")

                            {

                                object _serviceinsert = _fieldlist[z].getvalue(_insertobject);

                                if (_serviceinsert != null)

                                {

                                    p_servicename = ((serviceinstaller)_serviceinsert).servicename;

                                    return "";

                                }

                            }

                        }

                return "";

                return ex.message;

二、解除安裝windows服務:

        private void uninstallservice(string filepath)

                if (serviceisexisted("servicename"))

                    //uninstall service

                    myassemblyinstaller.path = filepath;

                    myassemblyinstaller.uninstall(null);

                throw new exception("uninstallserviceerror/n" + ex.message);

三、判斷window服務是否存在:

        private bool serviceisexisted(string servicename)

            servicecontroller[] services = servicecontroller.getservices();

            foreach (servicecontroller s in services)

                if (s.servicename == servicename)

                    return true;

            return false;

四、啟動服務:

private void startservice(string servicename)

            if (serviceisexisted(servicename))

                system.serviceprocess.servicecontroller service = new system.serviceprocess.servicecontroller(servicename);

                if (service.status != system.serviceprocess.servicecontrollerstatus.running && service.status != system.serviceprocess.servicecontrollerstatus.startpending)

                    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(startserviceerror.replace("$s$", servicename));

另外方法

        /// <summary>

        /// 啟動服務

        /// <param name="servicename"></param>

        /// <returns></returns>

        public static bool servicestart(string servicename)

                servicecontroller service = new servicecontroller(servicename);

                if (service.status == servicecontrollerstatus.running)

                    timespan timeout = timespan.frommilliseconds(1000 * 10);

                    service.waitforstatus(servicecontrollerstatus.running, timeout);

            catch

                return false;

            return true;

五、停止服務:

        private void stopservice(string servicename)

                if (service.status == system.serviceprocess.servicecontrollerstatus.running)

                    service.stop();

                        if (service.status == system.serviceprocess.servicecontrollerstatus.stopped)

                            throw new exception(stopserviceerror.replace("$s$", servicename));

另外一方法:

        /// 停止服務

        /// <param name="servisename"></param>

        public static bool servicestop(string servisename)

                servicecontroller service = new servicecontroller(servisename);

                if (service.status == servicecontrollerstatus.stopped)

六 修改服務的啟動項

        /// 修改服務的啟動項 2為自動,3為手動

        /// <param name="starttype"></param>

        public static bool changeservicestarttype(int starttype, string servicename)

                registrykey regist = registry.localmachine;

                registrykey sysreg = regist.opensubkey("system");

                registrykey currentcontrolset = sysreg.opensubkey("currentcontrolset");

                registrykey services = currentcontrolset.opensubkey("services");

                registrykey servicesname = services.opensubkey(servicename, true);

                servicesname.setvalue("start", starttype);

七 擷取服務啟動類型

        /// 擷取服務啟動類型 2為自動 3為手動 4 為禁用

        public static string getservicestarttype(string servicename)

                return servicesname.getvalue("start").tostring();

                return string.empty;

八 驗證服務是否啟動  服務是否存在

        /// 驗證服務是否啟動

        public static bool serviceisrunning(string servicename)

            servicecontroller service = new servicecontroller(servicename);

            if (service.status == servicecontrollerstatus.running)

                return true;

            else

        /// 服務是否存在

        public static bool serviceexist(string servicename)

                string m_servicename = servicename;

                servicecontroller[] services = servicecontroller.getservices();

                foreach (servicecontroller s in services)

                    if (s.servicename.tolower() == m_servicename.tolower())

                        return true;

注:手動安裝window服務的方法:

在“visual studio 2005 指令提示”視窗中,運作:

安裝服務:installutil servicepath

卸除服務:installutil /u servicepath