在.net中,使用了配置文件(Windows程序:app.config; Web程序:web.config)来定义数据库的连接字符串。那么我们该如何来读取、解析并变更它呢?
1) 读取config文件中的字符串;
a) 首先必须在工程中添加对System.Configuration.dll 的引用;
b) System.Configuration.ConfigurationManager.ConnectionStrings(name).ConnectionString;
2) 解析字符串内容;
a) 首先必须在工程中添加对System.Configuration.dll,System.Data 的引用;
b) Dim builder As New System.Data.SqlClient.SqlConnectionStringBuilder(ConfigProvider.Instance.ConnectionString)
setting.Url = builder.DataSource
setting.UserName = builder.UserID
setting.Password = builder.Password
3) 变更字符串内容,并保存和应用新的字符串;
a) 首先必须在工程中添加对System.Configuration.dll,System.Data 的引用;
b)
'获取新的字符串内容;
Dim connectionString As String = GetNewConnectionString(setting.AppServerSetting)
'打开config文件;
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
'设置新的字符串内容;
config.ConnectionStrings.ConnectionStrings(DataProvider.Instance.Attributes("connectionStringName")).ConnectionString = connectionString
'保存到config文件中;
config.Save()
'刷新并应用新的字符串;
System.Configuration.ConfigurationManager.RefreshSection("connectionStrings")