参考:http://blog.csdn.net/shengxupeng/article/details/45534595
http://greatverve.cnblogs.com/archive/2011/07/18/app-config.html
using System;
using System.Collections.Generic;using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Configuration;
using System.IO;
namespace DataLoad
{
public partial class Service1 : ServiceBase
{
//定时器
System.Timers.Timer t = null;
public Service1()
{
InitializeComponent();
//启用暂停恢复
base.CanPauseAndContinue = true;
//每10分钟执行一次
t = new System.Timers.Timer(600000);
//设置是执行一次(false)还是一直执行(true);
t.AutoReset = true;
//是否执行System.Timers.Timer.Elapsed事件;
t.Enabled = true;
//到达时间的时候执行事件(theout方法);
t.Elapsed += new System.Timers.ElapsedEventHandler(theout);
}
protected override void OnStart(string[] args)
{
t.Start();
}
protected override void OnStop()
{
t.Stop();
}
//恢复服务执行
protected override void OnContinue(){
t.Start();
}
//暂停服务执行
protected override void OnPause() {
t.Stop();
}
public void WriteLog(string str)
{
using (StreamWriter sw = File.AppendText(@"d:\service.txt"))
{
sw.WriteLine(str);
sw.Flush();
}
}
public void theout(object source, System.Timers.ElapsedEventArgs e)
{
String servername = "";
String database = "";
String user = "";
String password = "";
string str = System.Reflection.Assembly.GetEntryAssembly().Location;
str = str.Substring(0, str.LastIndexOf("\\"));
try
{
//创建并初始化一个xml对象
XmlDocument xml = new XmlDocument();
//加载xml文件
xml.Load(str + @"\EFConfig.xml");
//读取节点
foreach (XmlNode node in xml.SelectNodes("/configuration/source"))
{
servername = node.SelectSingleNode("server").InnerText;
database = node.SelectSingleNode("database").InnerText;
user = node.SelectSingleNode("user").InnerText;
password = node.SelectSingleNode("password").InnerText;
}
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["SIMPEntities"].ConnectionString.ToString();
//新建一个连接字符串实例
string newConString =
"metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source="
+servername+";initial catalog="+database+";persist security info=True;user id="+user+";password="+password+";MultipleActiveResultSets=True;App=EntityFramework"";
ConnectionStringSettings mySettings=new ConnectionStringSettings("SIMPEntities", newConString, "System.Data.EntityClient");
// 打开可执行的配置文件*.exe.config
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//删除旧的字符串
config.ConnectionStrings.ConnectionStrings.Remove("SIMPEntities");
// 将新的连接串添加到配置文件中.
config.ConnectionStrings.ConnectionStrings.Add(mySettings);
// 保存对配置文件所作的更改
config.Save(ConfigurationSaveMode.Modified);
// 强制重新载入配置文件的ConnectionStrings配置节
ConfigurationManager.RefreshSection("connectionStrings");
}
catch (Exception ex)
{
WriteLog(ex.Message);
}
}
}
}