在Winform中动态读写app.config文件

1、  首先需要在项目中引用:System.Configuration

2、  通过OpenExeConfiguration()这个方法来对配置文件进行操作

     若当前项目的配置文件如下:

复制代码



    
        
        
        
        
        
        
        
        
        
        
    
    
        
    

复制代码

 

需要对上面appSettings的键值作修改,如下代码所示:

复制代码

string path = Application.StartupPath + "\\ASSEMLY.exe";
            Configuration config = ConfigurationManager.OpenExeConfiguration(path);
            config.AppSettings.Settings.Clear();

            config.AppSettings.Settings.Add("DataSource", this.DataSource);
            config.AppSettings.Settings.Add("InitialCatalog", this.InitialCatalog);
            config.AppSettings.Settings.Add("UserId", this.UserId);
            config.AppSettings.Settings.Add("Password", this.DePassword);
            config.AppSettings.Settings.Add("ConnectTimeout", this.ConnectTimeout.ToString());

            // 保存对配置文件所作的更改
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节
            ConfigurationManager.RefreshSection("appSettings");

复制代码

 

  其中它是不能直接修改健值的,是在修改之前要删除该键值,然后重新添加

  同是,上面的只是对AppSettings进行操作,其实也可以对ConnectionStrings、SectionGroups、Sections进行操作

 

读取所有的AppSettings的值

 

StringBuilder str = new StringBuilder();
str.Append("

");
AppSettingsReader reader =
new AppSettingsReader();


NameValueCollection appStgs =
ConfigurationManager.AppSettings;

string[] names =
ConfigurationManager.AppSettings.AllKeys;

String value = String.Empty;

for (int i = 0; i < appStgs.Count; i++)
{


string key = names[i];
if (key.IndexOf("WebSiteUser") >= 0)
{
value = (String)reader.GetValue(key, value.GetType());
string[] strValue = value.Split(',');
string webservices = strValue[0];
string method = strValue[1];
str.Append("

");
}

}
str.Append("

用户名webservices地址webservices方法名称
" + key.Replace("WebSiteUser", "") + "" + webservices + "" + method + "
");
ViewData["ListWebSiteUser"] = str;
return View();

Winform—C#读写config配置文件

现在FrameWork2.0以上使用的是:ConfigurationManager或WebConfigurationManager。并且AppSettings属性是只读的,并不支持修改属性值.

一、如何使用ConfigurationManager?

1、添加引用:添加System.configguration

2、引用空间

3、config配置文件配置节

常用配置节:

(1)普通配置节

 

  

 

(2)数据源配置节


  

(3)自定义配置节

在Winform中动态读写app.config文件_第1张图片

 

 

二、config文件读写

1、依据连接串名字connectionName返回数据连接字符串  

复制代码

//依据连接串名字connectionName返回数据连接字符串  
        public static string GetConnectionStringsConfig(string connectionName)
        {
            //指定config文件读取
            string file = System.Windows.Forms.Application.ExecutablePath;
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            string connectionString =
                config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString();
            return connectionString;
        }

复制代码

2、更新连接字符串  

复制代码

/// 
        ///更新连接字符串  
        /// 
        ///连接字符串名称 
        ///连接字符串内容 
        ///数据提供程序名称 
        public static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)
        {
            //指定config文件读取
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);

            bool exist = false; //记录该连接串是否已经存在  
            //如果要更改的连接串已经存在  
            if (config.ConnectionStrings.ConnectionStrings[newName] != null)
            {
                exist = true;
            }
            // 如果连接串已存在,首先删除它  
            if (exist)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            //新建一个连接字符串实例  
            ConnectionStringSettings mySettings =
                new ConnectionStringSettings(newName, newConString, newProviderName);
            // 将新的连接串添加到配置文件中.  
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("connectionStrings");
        }

复制代码

3、返回*.exe.config文件中appSettings配置节的value项  

复制代码

/// 
        ///返回*.exe.config文件中appSettings配置节的value项  
        /// 
        /// 
        /// 
        public static string GetAppConfig(string strKey)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value.ToString();
                }
            }
            return null;
        }

复制代码

4、在*.exe.config文件中appSettings配置节增加一对键值对  

复制代码

///  
        ///在*.exe.config文件中appSettings配置节增加一对键值对  
        ///  
        ///  
        ///  
        public static void UpdateAppConfig(string newKey, string newValue)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            bool exist = false;
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == newKey)
                {
                    exist = true;
                }
            }
            if (exist)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            config.AppSettings.Settings.Add(newKey, newValue);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

复制代码

5、修改IP地址

// 修改system.serviceModel下所有服务终结点的IP地址
        public static void UpdateServiceModelConfig(string configPath, string serverIP)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
            ConfigurationSectionGroup sec = config.SectionGroups["system.serviceModel"];
            ServiceModelSectionGroup serviceModelSectionGroup = sec as ServiceModelSectionGroup;
            ClientSection clientSection = serviceModelSectionGroup.Client;
            foreach (ChannelEndpointElement item in clientSection.Endpoints)
            {
                string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
                string address = item.Address.ToString();
                string replacement = string.Format("{0}", serverIP);
                address = Regex.Replace(address, pattern, replacement);
                item.Address = new Uri(address);
            }

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("system.serviceModel");
        }

        // 修改applicationSettings中App.Properties.Settings中服务的IP地址
        public static void UpdateConfig(string configPath, string serverIP)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
            ConfigurationSectionGroup sec = config.SectionGroups["applicationSettings"];
            ConfigurationSection configSection = sec.Sections["DataService.Properties.Settings"];
            ClientSettingsSection clientSettingsSection = configSection as ClientSettingsSection;
            if (clientSettingsSection != null)
            {
                SettingElement element1 = clientSettingsSection.Settings.Get("DataService_SystemManagerWS_SystemManagerWS");
                if (element1 != null)
                {
                    clientSettingsSection.Settings.Remove(element1);
                    string oldValue = element1.Value.ValueXml.InnerXml;
                    element1.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP);
                    clientSettingsSection.Settings.Add(element1);
                }

                SettingElement element2 = clientSettingsSection.Settings.Get("DataService_EquipManagerWS_EquipManagerWS");
                if (element2 != null)
                {
                    clientSettingsSection.Settings.Remove(element2);
                    string oldValue = element2.Value.ValueXml.InnerXml;
                    element2.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP);
                    clientSettingsSection.Settings.Add(element2);
                }
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("applicationSettings");
        }

        private static string GetNewIP(string oldValue, string serverIP)
        {
            string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
            string replacement = string.Format("{0}", serverIP);
            string newvalue = Regex.Replace(oldValue, pattern, replacement);
            return newvalue;
        }

修改IP地址

 

config 读写方法

复制代码

using System.Configuration;
//省略其他代码
public SalesOrderData()
        {
            string str = "";
            str = ConfigurationManager.ConnectionStrings["kyd"].ToString();
            conn = new SqlConnection(str);
            cmd = conn.CreateCommand();
        }

复制代码

 实际应用:

1、获取配置节的值

button1 点击获取配置节指定key的value值

button2 点击获取配置节指定name的connectionString值

在Winform中动态读写app.config文件_第2张图片

在Winform中动态读写app.config文件_第3张图片

在Winform中动态读写app.config文件_第4张图片

结果为:

在Winform中动态读写app.config文件_第5张图片

2、修改配置节的值

button1 点击获取配置节指定key的value值

button2 点击修改配置节指定key的value值为文本框的值

button3 点击获取配置节指定key新的value值

在Winform中动态读写app.config文件_第6张图片

在Winform中动态读写app.config文件_第7张图片

在Winform中动态读写app.config文件_第8张图片

结果为:

 在Winform中动态读写app.config文件_第9张图片

此时配置文件key1的value值为,获取key值仍为修改前的值

在Winform中动态读写app.config文件_第10张图片

如何重置为修改前的值?

如何保存修改后的值?

在Winform中动态读写app.config文件_第11张图片

你可能感兴趣的:(Winform技术类)