使用C#创建WindowsService(Windows服务):定期执行Dos命令或Bat(批处理)文件

作者: 国双全 QQ:396068801,Email:guo200612@126.com

转载请注明出处

说明:

服务名:epAgentService

运行环境:Framework2.0
文件说明:
install.bat 安装服务
UnInstall.bat 删除服务
config.ini 配置文件

配置文件说明:
[settings]
batPath  BAT文件路径,例:d:/1.bat
[intervalsetting]
interval=5 间隔时间,单位:秒。例:5,表示5秒钟执行一次。

注意事项:
在首次执行循环时,杀毒软件可能会有提示,默认是允许执行。但如果用户手动禁止就没办法了。

 

 

Service1.cs

-----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
//////////////////////////////


using System.IO;

using System.Text.RegularExpressions;


namespace WindowsService_dos
{
    public partial class Service1 : ServiceBase
    {
   
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            timer1.Enabled = true;
            timer1.Interval = 10000;//单位:MS
            timer1.Start();
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            try
            {
                timer1.Enabled = false;
                timer1.Stop();
            }
            catch
            {

            }
        }


        public static void WriteLog(string strLog)
        {
            EventLog log = new EventLog();
            log.Source = "epAgentService";
            log.WriteEntry(strLog);
            //////////
            //EventLog log = new EventLog("epAgentService");

            //  首先应判断日志来源是否存在,一个日志来源只能同时与一个事件绑定s
            //if (!EventLog.SourceExists("epAgentServiceSource"))
            //    EventLog.CreateEventSource("epAgentServiceSource", "epAgentService");
            //log.Source = "epAgentServiceSource";
            //log.WriteEntry(strLog, EventLogEntryType.Information);
        }

 

        /// <summary>
        /// 执行DOS命令,返回DOS命令的输出
        /// </summary>
        /// <param name="dosCommand">dos命令</param>
        /// <param name="milliseconds">等待命令执行的时间(单位:毫秒),如果设定为0,则无限等待</param>
        /// <returns>返回输出,如果发生异常,返回空字符串</returns>
        public static string ExecuteDos(string dosCommand, int milliseconds)
        {

            string output = ""; //输出字符串
            if (dosCommand != null && dosCommand != "")
            {
                Process process = new Process(); //创建进程对象
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "cmd.exe"; //设定需要执行的命令
                startInfo.Arguments = "/C " + dosCommand; //设定参数,其中的“/C”表示执行完命令后马上退出
                startInfo.UseShellExecute = false; //不使用系统外壳程序启动
                startInfo.RedirectStandardInput = false; //不重定向输入
                startInfo.RedirectStandardOutput = true; //重定向输出
                startInfo.CreateNoWindow = true; //不创建窗口
                process.StartInfo = startInfo;

                try
                {
                    if (process.Start()) //开始进程
                    {
                        if (milliseconds == 0)
                            process.WaitForExit(); //这里无限等待进程结束
                        else
                            process.WaitForExit(milliseconds); //这里等待进程结束,等待时间为指定的毫秒
                        output = process.StandardOutput.ReadToEnd();//读取进程的输出
                    }
                }
                catch
                {
                    WriteLog("Dos命令" + dosCommand + "执行失败,时间" + DateTime.Now.ToString());
                }
                finally
                {
                    if (process != null)
                        process.Close();
                }
            }

            return output;

        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

            timer1.Enabled = false;
            try
            {
                string iniPath = AppDomain.CurrentDomain.BaseDirectory + "config.ini";
                INIClass clsIni = new INIClass(iniPath);
                if (clsIni.ExistINIFile())
                {
                    //string batPath = ConfigurationSettings.AppSettings["batPath"];
                    try
                    {
                        string batPath = clsIni.IniReadValue("settings", "batPath").ToString();

                        //int interval = 5;
                        int interval = Int32.Parse(clsIni.IniReadValue("intervalsetting", "interval").ToString()) * 1000;//间隔时间
                        if (batPath == null || batPath == "")
                        {
                            WriteLog("Dos命令获取失败,时间" + DateTime.Now.ToString());
                        }
                        else
                        {
                            WriteLog("开始执行" + batPath + ",开始时间" + DateTime.Now.ToString());
                        }
                        try
                        {
                            string str = ExecuteDos(batPath, interval);
                            WriteLog(str);
                        }
                        catch
                        {
                            WriteLog("执行" + batPath + "失败,时间" + DateTime.Now.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteLog("错误:"+ex.Message);
                    }
                }
                else
                {
                    WriteLog("INI文件不存在:"+iniPath);
                }

            }
            catch(Exception ex)
            {
                WriteLog("配置文件不存在,时间" + DateTime.Now.ToString()+".错误信息:"+ex.Message);
            }
            timer1.Enabled = true;
        }


    }
}

-----------------------------------------------------------------------------

 

---------------Service1.Designer.cs-------------------

namespace WindowsService_dos
{
    partial class Service1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.timer1 = new System.Timers.Timer();
            ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
            //
            // timer1
            //
            this.timer1.Enabled = true;
            this.timer1.Interval = 5000;
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
            //
            // Service1
            //
            this.ServiceName = "Service1";
            ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();

        }

        #endregion

        private System.Timers.Timer timer1;
    }
}
--------------------------------------------

读写INI文件类:INIClass.cs

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace WindowsService_dos
{
    public class INIClass
    {
        public string inipath;
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="INIPath">文件路径</param>
        public INIClass(string INIPath)
        {
            inipath = INIPath;
        }
        /// <summary>
        /// 写入INI文件
        /// </summary>
        /// <param name="Section">项目名称(如 [TypeName] )</param>
        /// <param name="Key">键</param>
        /// <param name="Value">值</param>
        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.inipath);
        }
        /// <summary>
        /// 读出INI文件
        /// </summary>
        /// <param name="Section">项目名称(如 [TypeName] )</param>
        /// <param name="Key">键</param>
        public string IniReadValue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(500);
            int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath);
            return temp.ToString();
        }
        /// <summary>
        /// 验证文件是否存在
        /// </summary>
        /// <returns>布尔值</returns>
        public bool ExistINIFile()
        {
            return File.Exists(inipath);
        }
    }

}
---------------------------------

 

---------配置文件:config.ini--------------

[settings]
batPath=d:/1.bat
[intervalsetting]
interval=3

-------------------------------------------------------

说明:

服务名:epAgentService

运行环境:Framework2.0
文件说明:
install.bat 安装服务
UnInstall.bat 删除服务
config.ini 配置文件

配置文件说明:
[settings]
batPath  BAT文件路径,例:d:/1.bat
[intervalsetting]
interval=5 间隔时间,单位:秒。例:5,表示5秒钟执行一次。

注意事项:
在首次执行循环时,杀毒软件可能会有提示,默认是允许执行。但如果用户手动禁止就没办法了。
----------------------------------------

安装调试:

 -----------Install.bat------------

%WINDIR%/Microsoft.NET/Framework/v2.0.50727/installUtil WindowsService_dos.exe
net start "epAgentService"
pause
-----------UnInstall.bat-------

%WINDIR%/Microsoft.NET/Framework/v2.0.50727/installUtil /u WindowsService_dos.exe
net start "epAgentService"
pause

------------------------------------------------------

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值