有时候我们需要在程序中动态的修改Web.config文件,这里我提供一个类来对Web.config文件进行动态的操作。
public abstract class AppControl { public static void UpdateConnectionString(string newName,string newConString,string newProviderName,string path) { string[] strs = path.Split( '\\' ); string exePath = strs[ strs.Length - 2 ]; ConnectionStringSettings mySettings = new ConnectionStringSettings(newName, newConString, newProviderName); Configuration config = WebConfigurationManager.OpenWebConfiguration( "/" + exePath ); config.ConnectionStrings.ConnectionStrings.Remove(newName); config.ConnectionStrings.ConnectionStrings.Add(mySettings); config.ConnectionStrings.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection( "connectionStrings" ); }
}
"newName"是你要修改的connectionString的名字,“newConString” 是新的连接字符串,“path”是web.config文件所在的文件夹的全路径。
<connectionStrings> <add name="constr" connectionString="server=10.0.0.0;database=zz;uid=sa;pwd=sa;"/> </connectionStrings>
修改Web.config
string strSql = "server=.;database=test;uid=sa;pwd=sa"; AppControl.UpdateConnectionString( "constr", strSql, "", path );