コード例 #1
0
 /// <summary>
 /// 获取logger实例
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public static AppDomainLogger CreateLogger(string name)
 {
     if (logger == null)
     {
         logger = new AppDomainLogger(name);
     }
     return(logger);
 }
コード例 #2
0
        /// <summary>
        /// Open or create a config file with specify content in xmlFile.
        /// </summary>
        /// <param name="path">Path to create config file.</param>
        /// <param name="createIfNotExist">Create a new configure file if not exist.</param>
        /// <param name="initialContent">The initial content for new create file, should not contain xml header.</param>
        public ConfigureFile(string path, bool createIfNotExist, string initialContent = null)
        {
            this.log  = AppDomainLogger.CreateLogger(Process.GetCurrentProcess().ProcessName);
            this.path = path;

            // create a new config file when not exist.
            if (!File.Exists(path))
            {
                if (createIfNotExist)
                {
                    log.Debug("Configure file not exist, path: {0}. Try to create one.", path);
                    try
                    {
                        using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            string xmlContent;
                            if (!string.IsNullOrEmpty(initialContent))
                            {
                                xmlContent = string.Format("{0}\r\n{1}\r\n{2}", xmlInitialHeader, initialContent, xmlInitialTail);
                            }
                            else
                            {
                                xmlContent = string.Format("{0}\r\n{1}", xmlInitialHeader, xmlInitialTail);
                            }
                            var data = Encoding.UTF8.GetBytes(xmlContent);
                            stream.Write(data, 0, data.Length);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("Fail to create xml file. Exception: {0}", ex.ToString());
                        throw new Exception("Fail to create xml file");
                    }
                }
                else
                {
                    var msg = string.Format("File not found, path: {0}.", path);
                    log.Error(msg);
                    throw new Exception(msg);
                }
            }

            try
            {
                doc = new XmlDocument();
                doc.Load(path);
                rootNode = doc.DocumentElement;
            }
            catch (Exception ex)
            {
                log.Error("Fail load xml file. Exception: {0}", ex.ToString());
                throw new Exception("Fail load xml file.");
            }
        }