• App Config 配置文件的读写操作


    若需要修改则可以打开配置文件,操作节点属性。App.config 配置文件是项目自带的xml文件, 可以使用 .net自带的类ConfigurationManager去访问,但首先需要引入System.Configuration 类库。在该配置文件中,常用的配置节点有3种:

    1. 数据库连接字符串节点  connectionStrings

      <connectionStrings>
        <add name="HolipERP" connectionString="Server=cnhay01as02;User ID=hlpsfs;Password=8nasalt;Database=sfsData;" providerName="SQLOLEDB.1"/>
        <add name="TestData" connectionString="Server=cnhay01as01;User ID=production;Password=holipserver;Database=Test_Memo_Data;" providerName="SQLOLEDB.1" />
      </connectionStrings>

    可用 ConfigurationManager.ConnectionStrings[name].ToString() 读取connectionString属性 ,好像找不到直接修改的方法,我是采用先删除再添加的方式修改的,其实一般也不会在程序里面动态修改这个配置字节。

    2. 系统参数配置  AppSettings

      <appSettings>
        <add key="PLC_IP" value="192.168.0.11" />
      </appSettings>

    这种配置是以键值对的方式存在的,可用 ConfigurationManager.AppSettings[key].ToString() 读取 value 值, 若需要修改则可以打开配置文件,操作节点属性。

    Configuration appConfig =  ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);   //打开 vshost.exe.config
    appConfig.AppSettings.Settings.Add(key, value);
    appConfig.AppSettings.Settings.Remove(key);
    appConfig.AppSettings.Settings[key].Value = value;

    3. 自定义配置 configSections

    常用的有3种类型:    System.Configuration.SingleTagSectionHandler (属性值的方式)

                                     System.Configuration.DictionarySectionHandler  (键值对的方式)

                                     System.Configuration. NameValueSectionHandler  (键值对的方式)

    可以加上分组标签,另外有点很重要,configSections配置节必须放在开头即configuration的第一个子元素,具体配置格式如下,

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <sectionGroup name="PLCData">
          <section name="serialNum" type="System.Configuration.SingleTagSectionHandler"/>
          <section name="enableAssemble" type="System.Configuration.SingleTagSectionHandler"/>
        </sectionGroup>
        <section name="example1" type="System.Configuration.NameValueSectionHandler "/>
      </configSections>
      <PLCData>
        <serialNum DB="2" StartAddr="0" ByteLength="18" />
        <enableAssemble DB="2" StartAddr="18" ByteLength="2" />
      </PLCData>
      <example1>
        <add key="Hello" value="World" />
        <add key="Good" value="Morning" />
      </example1>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
      </startup>
      <connectionStrings>
        <add name="HolipERP" connectionString="Server=cnhay01as02;User ID=hlpsfs;Password=8nasalt;Database=sfsData;" providerName="SQLOLEDB.1"/>
        <add name="TestData" connectionString="Server=cnhay01as01;User ID=production;Password=holipserver;Database=Test_Memo_Data;" providerName="SQLOLEDB.1" />
      </connectionStrings>
      <appSettings>
        <add key="PLC_IP" value="192.168.0.11" />
      </appSettings>
    </configuration>

     可通过 IDictionary IDic = (IDictionary)ConfigurationManager.GetSection(setionGroupName+"/"+setionName) 读取配置,以键值对的方式保存。若需要修改,可采用xPath方式直接访问。下面这个AppConfigManagement静态类,当中的修改方法都是同时更新保存两个配置文件的,原因注释里有写到。

       /// <summary>
        /// winform会自动生成有2个配置文件 vshost.exe.config 和  exe.config,  修改操作必须同时修改2个文件并同时保存, 如果只修改vshost.exe.config,程序重启会重新读取exe.config将其覆盖
        /// </summary>
        public static class AppConfigManagement
        {
            private static Configuration appConfig = null;   // vshost.exe.config
    
            private static Configuration appConfig_original = null;   // exe.config
    
            private static XmlDocument doc = null;       //加载 vshost.exe.config
    
            static AppConfigManagement()
            {
                appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);   //打开 vshost.exe.config
                appConfig_original = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);   //打开 exe.config
                doc = new XmlDocument();       //加载 vshost.exe.config
                doc.Load(appConfig.FilePath);
            }
    
            //读取连接字符串
            public static string GetConnectionStringSet(string name)
            {
                try
                {
                    return ConfigurationManager.ConnectionStrings[name].ToString();
                }catch(Exception err){
                    throw new Exception("GetConnectionStringSet:" + err.Message);
                }
            }
            //修改连接字符串
            public static void SetConnectionStringSet(string name,string value)
            {
                try
                {
                    appConfig.ConnectionStrings.ConnectionStrings.Remove(name);                 //没有直接修改的方法,只能先删除,再创建     vshost.exe.config
                    appConfig_original.ConnectionStrings.ConnectionStrings.Remove(name);        //     .exe.config
                    appConfig.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(name, value));         //添加vshost.exe.config
                    appConfig_original.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(name, value));         //添加exe.config
                    appConfig.Save();                     //保存vshost.exe.config
                    appConfig_original.Save();                     //保存exe.config
                    ConfigurationManager.RefreshSection("connectionStrings");   //刷新内存中的配置值
                    if (!(GetConnectionStringSet(name) == value))
                    {             //读取比较确认修改成功
                        throw new Exception("Failed to SetConnectionStringSet");
                    }
                }
                catch (Exception err)
                {
                    throw new Exception("SetConnectionStringSet:" + err.Message);
                }
            }
            //读取程序配置
            public static string GetAppSeting(string name)
            {
                try
                {
                    return ConfigurationManager.AppSettings[name].ToString();
                }
                catch (Exception err)
                {
                    throw new Exception("GetAppSeting:" + err.Message);
                }
            }
            //添加程序配置
            public static void AddAppSeting(string key,string value)
            {
                try
                {
                    appConfig.AppSettings.Settings.Add(key, value);
                    appConfig_original.AppSettings.Settings.Add(key, value);
                    appConfig.Save();                     //保存
                    appConfig_original.Save();                     //保存
                    ConfigurationManager.RefreshSection("appSettings");
                    if (!(GetAppSeting(key) == value))
                    {             //读取比较确认添加成功
                        throw new Exception("Failed to AddAppSeting");
                    }
                }
                catch (Exception err)
                {
                    throw new Exception("AddAppSeting:" + err.Message);
                }
            }
            //删除程序配置
            public static void DeleteAppSeting(string key)
            {
                try
                {
                    appConfig.AppSettings.Settings.Remove(key);
                    appConfig_original.AppSettings.Settings.Remove(key);
                    appConfig.Save();                     //保存
                    appConfig_original.Save();                     //保存
                    ConfigurationManager.RefreshSection("appSettings");
                }
                catch (Exception err)
                {
                    throw new Exception("DeleteAppSeting:" + err.Message);
                }
            }
            //修改程序配置
            public static void UpdateAppSeting(string key,string value)
            {
                try
                {
                    appConfig.AppSettings.Settings[key].Value = value;
                    appConfig_original.AppSettings.Settings[key].Value = value;
                    appConfig.Save();                     //保存
                    appConfig_original.Save();                     //保存
                    ConfigurationManager.RefreshSection("appSettings");
                    if (!(GetAppSeting(key) == value))
                    {             //读取比较确认添加成功
                        throw new Exception("Failed to UpdateAppSeting");
                    }
                }
                catch (Exception err)
                {
                    throw new Exception("UpdateAppSeting:" + err.Message);
                }
            }
            //读取自定义配置节
            //读取System.Configuration.SingleTagSectionHandler类型,System.Configuration.NameValueSectionHandler类型和System.Configuration.DictionarySectionHandler类型自定义配置节
            public static Dictionary<string, string> GetCustomizedSection(string setionName)
            {
                try
                {
                    IDictionary IDic = (IDictionary)ConfigurationManager.GetSection(setionName);
                    Dictionary<string,string> Dic_Copy = new Dictionary<string,string>();           
                    foreach(object key in IDic.Keys){
                        Dic_Copy.Add(key.ToString(),IDic[key].ToString());
                    }
                    return Dic_Copy;
                }
                catch (Exception err)
                {
                    throw new Exception("GetCustomizedSection:" + err.Message);
                }
            }
            //读取分组的System.Configuration.SingleTagSectionHandler类型,System.Configuration.NameValueSectionHandler类型和System.Configuration.DictionarySectionHandler类型自定义配置节
            public static Dictionary<string, string> GetCustomizedSection(string setionGroupName,string setionName)
            {
                try
                {
                    IDictionary IDic = (IDictionary)ConfigurationManager.GetSection(setionGroupName+"/"+setionName);
                    Dictionary<string, string> Dic_Copy = new Dictionary<string, string>();
                    foreach (object key in IDic.Keys)
                    {
                        Dic_Copy.Add(key.ToString(), IDic[key].ToString());
                    }
                    return Dic_Copy;
                }
                catch (Exception err)
                {
                    throw new Exception("GetCustomizedSection:" + err.Message);
                }
            }
            //修改System.Configuration.SingleTagSectionHandler类型自定义配置节
            public static void SetCustomizedSectionProperty(string setionGroup,string setionName, string propertyName, string value)
            {
                try
                {
                    string xpath = "";
                    if (string.IsNullOrEmpty(setionGroup))      //是否有组
                    {
                        xpath = setionName;
                    }
                    else
                    {
                        xpath = setionGroup + "/" + setionName;
                    }
                    XmlNode node = doc.SelectSingleNode(@"/configuration/"+xpath);    //使用xPath的方式直接访问
                    node.Attributes[propertyName].Value = value;     //设置属性值
                    doc.Save(appConfig.FilePath);                    //保存至 vshost.exe.config
                    doc.Save(appConfig_original.FilePath);                    //保存至 exe.config
                    ConfigurationManager.RefreshSection(xpath);      //刷新内存中的配置值
                }
                catch (Exception err)
                {
                    throw new Exception("SetSingleTagSectionValue:" + err.Message);
                }
            }
        }
  • 相关阅读:
    455. Assign Cookies
    [leetcode]Linked List Cycle
    *[topcoder]GooseTattarrattatDiv1
    [topcoder]FoxAndChess
    *[topcoder]TheTree
    *[topcoder]LittleElephantAndBalls
    *[topcoder]HexagonalBoard
    *[topcoder]AstronomicalRecords
    *[topcoder]LittleElephantAndIntervalsDiv1
    [topcoder]IncrementAndDoubling
  • 原文地址:https://www.cnblogs.com/change-myself/p/11352931.html
Copyright © 2020-2023  润新知