一、添加连接字符串
在Setting设计器中添加 ConnectionString 类型的配置
二、读取
三、修改
如果是 User 范围
恢复默认值
如果是Application 范围
1、直接修改app.config文件
2、编程修改XML文档
使用扩展函数
调用
修改后,重新读取最新的配置
在Setting设计器中添加 ConnectionString 类型的配置
二、读取
System.Configuration.ConnectionStringSettingsCollection config = System.Configuration.ConfigurationManager.ConnectionStrings;
for (int i = 0; i < config.Count; i++)
{
if (config[i].Name.Equals("TestDBConnectionString", StringComparison.OrdinalIgnoreCase))
{
return config[i].ToString();
}
}
for (int i = 0; i < config.Count; i++)
{
if (config[i].Name.Equals("TestDBConnectionString", StringComparison.OrdinalIgnoreCase))
{
return config[i].ToString();
}
}
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings[1].ConnectionString);
三、修改
如果是 User 范围
Properties.Settings.Default.Save();
恢复默认值
Properties.Settings.Default.Reset();
如果是Application 范围
1、直接修改app.config文件
2、编程修改XML文档
使用扩展函数
static class ConfigTools
{
public static void SetConnectionString(this global::System.Configuration.ApplicationSettingsBase curApplicationSettingsBase, string connectString)
{
XElement doc = XElement.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var result = (from c in doc.Descendants("connectionStrings").Descendants("add").Attributes("connectionString")
select c).First();
result.Value = connectString;
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
}
{
public static void SetConnectionString(this global::System.Configuration.ApplicationSettingsBase curApplicationSettingsBase, string connectString)
{
XElement doc = XElement.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var result = (from c in doc.Descendants("connectionStrings").Descendants("add").Attributes("connectionString")
select c).First();
result.Value = connectString;
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
}
调用
Settings.Default.SetConnectionString(newConnectionString);
修改后,重新读取最新的配置
Properties.Settings.Default.Reload();