Monitor implementation of the specified configuration file, configuration changes immediately get the latest configuration and use

// function to achieve the following code: The program automatically creates the configuration file, and update the associated configuration classes immediately when the contents of the configuration file is changed, so that the program made when calling the configuration class is the latest configuration content without having to restart the program. 

the using
the System; the using the System.Collections.Generic; the using the System.IO; the using the System.Linq; the using the System.Text; namespace xxxxx.MessageHandling.Config { public class MessageHandlerConfig { public MessageHandlerConfig () { var the dir = AppDomain.CurrentDomain.BaseDirectory + " Config \\ " ; IF (! Directory.Exists (dir)) Directory.CreateDirectory (dir); this.ConfigFilePath = AppDomain.CurrentDomain.BaseDirectory + "Config\\messageHandler.config"; if (!File.Exists(this.ConfigFilePath)) { this.MailServiceUrl = "http://ip1:8001/api/MailService"; this.ConnectionString = @"Data Source=CL01-SQL-01\SQL1;Initial Catalog={dbName};uid=TCITClient;pwd=B532!!;"; #if DEBUG this.MailServiceUrl = "http://ip2:8001/api/MailService"; this.ConnectionString = @"Data Source=CL01-SQL-01\SQL1;Initial Catalog={dbName};uid=demo;pwd=demo;"; #endif this.SendMailType = 0; this.saveConfig(); } else { this.readConfig(); } this.configFileLastWriteTime = new FileInfo(this.ConfigFilePath).LastWriteTime; FileSystemWatcher fsw = new FileSystemWatcher(dir); fsw.NotifyFilter = NotifyFilters.LastWrite; fsw.Filter = "messageHandler.config"; fsw.Changed += Fsw_Changed; fsw.EnableRaisingEvents = true; } private void Fsw_Changed(object sender, FileSystemEventArgs e) { if (e.ChangeType != WatcherChangeTypes.Changed) return; var lastUpdateTime = new FileInfo(e.FullPath).LastWriteTime; if (lastUpdateTime == this.configFileLastWriteTime) return ; the else the this .configFileLastWriteTime = LastUpdateTime; Console.WriteLine ( " Config File the Update: " + LastUpdateTime); the this .readConfig (); } /// <Summary> /// profile path /// </ Summary> protected String ConfigFilePath { GET ; SET ;} /// <Summary> /// configuration file was last modified time /// </ Summary> Private the DateTime configFileLastWriteTime { GET ; SET ;} /// <Summary> /// send mail by: /// 0 - direct SMTP transmission start mode /// 1-- mail service sent by a call /// </ Summary> public byte SendMailType { GET ; protected SET ;} / // <Summary> /// URL address of the message service /// </ Summary> public string MailServiceUrl { GET ; protected SET ;} /// <Summary> /// database link string /// </ Summary> protected String the ConnectionString { GET ; SET ;} Private BOOL _isUploadMailTemplates; /// <Summary> /// Whether there will be uploaded to the database through the mail template /// </ Summary> public BOOL IsUploadMailTemplates { GET { return _isUploadMailTemplates; } SET { IF (value =! _isUploadMailTemplates) { _isUploadMailTemplates = value; the this .saveConfig (); } } } /// <summary> /// 获取数据库链接字符串 /// </summary> /// <param name="dbName"></param> /// <returns></returns> public string GetConnectionString(string dbName) { return this.ConnectionString.Replace("{dbName}", dbName); } private void readConfig() { FileStream fs = null; StreamReader sr = null; try { if (!File.Exists(this.ConfigFilePath)) return; fs = new FileStream(this.ConfigFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); sr = new StreamReader(fs, Encoding.UTF8); while (!sr.EndOfStream) { var str = sr.ReadLine(); var arr = str.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (arr.Length > 1) { try { var name = arr[0]; var val = this.mergeArray(arr, 1, '='); if (string.Equals(name, "IsUploadMailTemplates", StringComparison.OrdinalIgnoreCase)) this._isUploadMailTemplates = bool.Parse(val); if (string.Equals(name, "SendMailType", StringComparison.OrdinalIgnoreCase)) this.SendMailType = byte.Parse(val); else if (string.Equals(name, "ConnectionString", StringComparison.OrdinalIgnoreCase)) this.ConnectionString = val; else if (string.Equals(name, "MailServiceUrl", StringComparison.OrdinalIgnoreCase)) this.MailServiceUrl = val; } catch { } } } sr.Close(); fs.Close(); } catch { } finally { this.dispose(new IDisposable[] { sr, fs }); } } private string mergeArray(string[] array, int startIndex, char splitChar) { var sb = new StringBuilder(); if (array != null) { for (var i = startIndex; i < array.Length; i++) { if (i == startIndex) sb.Append(array[i]); else sb.Append(splitChar + array[i]); } } return sb.ToString(); } private void saveConfig() { FileStream fs = null; StreamWriter sw = null; try { if (!File.Exists(this.ConfigFilePath)) fs = new FileStream(this.ConfigFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); else fs = new FileStream(this.ConfigFilePath, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite); sw = new StreamWriter(fs, Encoding.UTF8); var sb = new StringBuilder(); sb.AppendLine($"IsUploadMailTemplates={IsUploadMailTemplates}"); sb.AppendLine($"SendMailType={SendMailType}"); sb.AppendLine($"MailServiceUrl={MailServiceUrl}"); sb.AppendLine($"ConnectionString={ConnectionString}"); sw.Write(sb.ToString()); sw.Flush(); fs.Flush(); sw.Close(); fs.Close(); } catch { } finally { this.dispose(new IDisposable[] { sw, fs }); } } private void dispose(IDisposable[] objs) { if (objs != null && objs.Length > 0) { for (var i = 0; i < objs.Length; i++) { var obj = objs[i]; try { if (obj != null) obj.Dispose(); } catch { } finally { obj = null; } } } } private void output() { Console.WriteLine("==============="); Console.WriteLine($"IsUploadMailTemplates={IsUploadMailTemplates}"); Console.WriteLine($"SendMailType={SendMailType}"); Console.WriteLine($"MailServiceUrl={MailServiceUrl}"); Console.WriteLine($"ConnectionString={ConnectionString}"); } } }

Call the above code places

/// <summary>
    /// 消息处理器
    /// </summary>
    public static class MessageHandler
    {
        private static readonly MessageHandlerConfig config = null;

        static MessageHandler()
        {
            try
            {
                config = new MessageHandlerConfig();
                uploadMailTemplates();
            }
            catch { }
        }

    private static void uploadMailTemplates()
        {
            if (config == null)
                return;

            if (config.IsUploadMailTemplates)
                return;

            //异步执行邮件保存
            Thread th = new Thread(new ThreadStart(() =>
            {
                try
                {
                    var hostName = Environment.UserDomainName + "\\" + Environment.MachineName + "\\" + Environment.UserName;

                    var baseDir = AppDomain.CurrentDomain.BaseDirectory;
                    var dir = new System.IO.DirectoryInfo(baseDir + "Config");
                    var files = dir.GetFiles("MessageHandling*.xml");
                    var list = new List<MessageHandlingData>();

                    if (files == null || files.Length == 0)
                        return;

                    foreach (var f in files)
                    {
                        var languageCode = string.Empty;
                        var arrFileNames = f.Name.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                        if (arrFileNames.Length == 3)
                            languageCode = arrFileNames[1];
                        if (arrFileNames.Length > 3)
                            continue;

                        FileStream fs = null;
                        StreamReader sr = null;
                        try
                        {
                            fs = new FileStream(f.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                            sr = new StreamReader(fs, Encoding.UTF8);
                            var strXml = sr.ReadToEnd();
                            var msgHandling = CommonHelper.DeSerialize<MessageHandlingData>(strXml);
                            foreach (var email in msgHandling.EmailList)
                            {
                                email.ServerName = hostName;
                                email.TemplateFileName = f.Name;
                                email.LanguageCode = languageCode;
                                email.BaseDirectory = baseDir;
                                email.FilePath = f.DirectoryName;
                            }
                            list.Add(msgHandling);

                            foreach (var msgHanding in list)
                            {
                                if (msgHanding == null || msgHanding.EmailList == null)
                                    continue;

                                foreach (var mail in msgHanding.EmailList)
                                {
                                    if (mail == null)
                                        continue;

                                    //save mail template to DB
                                    CommonHelper.SaveMailTemplate(config.GetConnectionString("TCITLog"), mail);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            CommonHelper.WriteLog(" Saved mail template matter abnormalities, Method SaveMailTemplates = (), File = ' + + f.FullName " , Exception = " + ex.ToString ()); 
                        } 
                        the finally 
                        { 
                            IF ! (SR = null ) 
                            { 
                                the try 
                                { 
                                    sr.Close (); 
                                    sr.Dispose (); 
                                } 
                                the catch {} 
                            } 
                            IF (! FS = null ) 
                            {
                                try
                                {
                                    fs.Close();
                                    fs.Dispose();
                                }
                                catch { }
                            }
                        }
                    }
                    config.IsUploadMailTemplates = true;
                }
                catch { }
            }));

            th.Start();
        }

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace xxxx.MessageHandling.Configuration
{
    [XmlRoot("messageHandling", Namespace = "http://tcghl.com/framework/messagehandling")]
    public class MessageHandlingData
    {
        [XmlElement("email")]
        public List<EmailTempData> EmailList { get; set; }
    }

    [Serializable]
    public class EmailTempData
    {
        [XmlAttribute("name")]
        public string TemplateName { get; set; }

        [XmlAttribute("subject")]
        public string Subject { get; set; }

        [XmlElement("body")]
        public string Body { get; set; }

        [XmlIgnore]
        public string BaseDirectory { get; set; }
        [XmlIgnore]
        public string LanguageCode { get; set; }
        [XmlIgnore]
        public string TemplateFileName { get; set; }
        [XmlIgnore]
        public string FilePath { get; set; }
        [XmlIgnore]
        public string ServerName { get; set; }
    }
}

Guess you like

Origin www.cnblogs.com/itjeff/p/12230543.html