首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何动态更改web.config中的连接字符串

要动态更改Web.config中的连接字符串,可以使用以下方法:

  1. 使用C#代码更改连接字符串:

在需要更改连接字符串的地方,使用以下代码:

代码语言:csharp
复制
ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString = "Data Source=newServerName;Initial Catalog=newDatabaseName;User ID=newUsername;Password=newPassword";

其中,ConnectionStringName是Web.config中连接字符串的名称,newServerNamenewDatabaseNamenewUsernamenewPassword分别是新的服务器名称、数据库名称、用户名和密码。

  1. 使用Web.config文件的configSource属性将连接字符串单独存储在一个XML文件中,然后使用C#代码更改该XML文件中的连接字符串。

首先,在Web.config文件中将连接字符串的configSource属性设置为一个单独的XML文件:

代码语言:xml<connectionStrings configSource="connections.config"/>
复制

然后,在connections.config文件中定义连接字符串:

代码语言:xml<connectionStrings>
复制
  <add name="ConnectionStringName" connectionString="Data Source=serverName;Initial Catalog=databaseName;User ID=username;Password=password" providerName="System.Data.SqlClient"/>
</connectionStrings>

接下来,使用以下代码更改connections.config文件中的连接字符串:

代码语言:csharp
复制
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Server.MapPath("~/connections.config");
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
configuration.ConnectionStrings.ConnectionStrings["ConnectionStringName"].ConnectionString = "Data Source=newServerName;Initial Catalog=newDatabaseName;User ID=newUsername;Password=newPassword";
configuration.Save();

其中,connections.config是连接字符串单独存储的XML文件的名称,newServerNamenewDatabaseNamenewUsernamenewPassword分别是新的服务器名称、数据库名称、用户名和密码。

需要注意的是,在使用这些方法更改连接字符串后,应用程序池需要重新启动才能使更改生效。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券