C# 开发Window服务

参考

https://jingyan.baidu.com/article/fa4125acb71a8628ac709226.html

http://www.cnblogs.com/sorex/archive/2012/05/16/2502001.html

注意

1、设置服务安装后自动启动

在serviceInstaller1的AfterInstall添加如下代码

private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
    System.ServiceProcess.ServiceController s = new System.ServiceProcess.ServiceController("你设置的服务名");
    s.Start();
}

2、windows服务不执行Timer控件的解决办法

        Timer timer = new Timer();
        public Service1()
        {
            InitializeComponent();
            timer.Interval = 2000;
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.AutoReset = true;//设置是执行一次(false),还是一直执行(true);
            timer.Enabled = true;
            timer.Start();
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            File.WriteAllText("D:\\text.txt", DateTime.Now.ToString() + "\r\n");
        }

3、设置允许服务与桌面交互方法

让服务启动某个应用程序,就要修改服务的属性,勾选允许服务与桌面交互

#region 设置服务与桌面交互

        /// <summary>
        /// 设置服务与桌面交互,在serviceInstaller1的AfterInstall事件中使用
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        private void SetServiceDesktopInsteract(string serviceName)
        {
            System.Management.ManagementObject wmiService = new System.Management.ManagementObject(string.Format

("Win32_Service.Name='{0}'", serviceName));
            System.Management.ManagementBaseObject changeMethod = wmiService.GetMethodParameters("Change");
            changeMethod["DesktopInteract"] = true;
            System.Management.ManagementBaseObject utParam = wmiService.InvokeMethod("Change", changeMethod,

null);
        }
        #endregion

 注意:windows服务中如果要使用log4net记录日志,必须在Properties下的AssemblyInfo.cs文件添加如下代码

[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]

控制台程序也一样

windows服务安装程序ProjectInstaller中

ConfigurationManager.AppSettings[]

不能获取App.config中配置解决办法

 

        /// <summary>
        /// 安装程序里面获取App.config中配置
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private static string GetAppSettingValue(string key)
        {
            var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetAssembly(typeof(ProjectInstaller)).Location);
            return config.AppSettings.Settings[key].Value;
        }

 

posted @ 2017-09-18 10:40  事理  阅读(192)  评论(1编辑  收藏  举报