简体   繁体   English

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

[英]how to change to connection string in web.config dynamically

I defind the connection string in web.config 我在web.config中定义连接字符串

     <ConnectionStrings>
 <add name="student" connectionString="Server=student;Max Pool Size=300;Initial Catalog=studentDB;User ID=student;Password=st123dent;" providerName="System.Data.SqlClient"/>
     </Connectionstrings>

how can i change the connection string dynamically in c# 如何在c#中动态更改连接字符串

Configuration is read only so you can not do it in obvious way like 配置是只读的,所以你不能以明显的方式做到这一点

ConfigurationManager.ConnectionStrings["student"].ConnectionString = "new value";

This raises System.Configuration.ConfigurationErrorsException exception which saying that "Configuration is read only". 这会引发System.Configuration.ConfigurationErrorsException异常,该异常表示“Configuration is read only”。

Here is a trick using reflection to reset readOnly attribute of configuration element. 这是一个使用反射来重置配置元素的readOnly属性的技巧。 See this article for full details Programmatically setting a connectionString property 有关完整详细信息,请参阅此文章以编程方式设置connectionString属性

Code snippet: 代码段:

var settings = ConfigurationManager.ConnectionStrings[ 0 ];
var fi = typeof(ConfigurationElement).GetField(
              "_bReadOnly", 
              BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(settings, false);
settings.ConnectionString = "Data Source=Something";

BTW, why you need change it the configuration? 顺便说一句,为什么你需要改变它的配置? I'm feeling that you'are trying to solve some problem in wrong way. 我觉得你试图以错误的方式解决一些问题。

You can open your Web.Config file for reading and writing using WebConfigurationManager.OpenWebConfiguration or WebConfigurationManager.OpenMappedWebConfiguration . 您可以使用WebConfigurationManager.OpenWebConfigurationWebConfigurationManager.OpenMappedWebConfiguration打开Web.Config文件以进行读取和写入。 And provided you have write permission you'll be able to make modifications such as changing the connection string. 如果您具有写入权限,则可以进行修改,例如更改连接字符串。

This surely has to be better than using reflection to modify a private field. 这肯定比使用反射修改私有字段更好。

Modifying web.config will then recycle the web application, so this isn't suitable for letting users make changes to web.config - though it could be used in specific scenarios such as deployment. 然后,修改web.config将回收Web应用程序,因此这不适合让用户对web.config进行更改 - 尽管它可以在特定方案(如部署)中使用。

Example: 例:

var configurationFileInfo = new FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var vdm = new VirtualDirectoryMapping(configurationFileInfo.DirectoryName, true, configurationFileInfo.Name);
var wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
Configuration config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");

ConnectionStringsSection section = config.GetSection("connectionStrings") 
                         as ConnectionStringsSection;
if (section != null)
{
    ... modify the section ...
    config.Save();
}

Use NameSpace 使用NameSpace

using System.Configuration;
using System.Web.Configuration;


void ConfigurnewConnectionString(string server, string database, string userid, string password)
    {


    string str = "server=" + server + ";database=" + database + "; User ID=" + userid + "; Password=" + password + "";
    //Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
    //str = System.Web.Configuration.WebConfigurationManager.AppSettings["myKey"];
    //myConfiguration.Save();
    System.Configuration.Configuration Config1 = WebConfigurationManager.OpenWebConfiguration("~");
    ConnectionStringsSection conSetting = (ConnectionStringsSection)Config1.GetSection("connectionStrings");
    ConnectionStringSettings StringSettings = new ConnectionStringSettings("conn", "Data Source=" + server + ";Database=" + database + ";User ID=" + userid + ";Password=" + password + ";");
    conSetting.ConnectionStrings.Remove(StringSettings);
    conSetting.ConnectionStrings.Add(StringSettings);
    Config1.Save(ConfigurationSaveMode.Modified);
    //Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
    //myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text;
    //myConfiguration.Save();
}

in Web Confige put this code 在Web Confige中输入此代码

<add name="yourconnectionname" connectionString="Data Source={0};Initial Catalog={1};User ID={2};Password={3}" providerName="System.Data.SqlClient"/>

in your connection put this code 在您的连接中放置此代码

 string ScrtCon = ConfigurationManager.ConnectionStrings["yourconnectionname"].ToString();
ScrtCon = string.Format(ScrtCon, "Server Name","Data base Name",  "Database User Name", "Database password");

If a user is able to change the value of the Setting, then the web.config file is the wrong place to store the setting. 如果用户能够更改设置的值,则web.config文件是存储设置的错误位置。

You should check out a User Scoped value in a Settings file instead. 您应该在设置文件中签出用户范围值。

MSDN - Using Settings in C MSDN - 在C中使用设置

When using settings like this, changing the value at runtime is easy: 使用这样的设置时,在运行时更改值很容易:

Properties.Settings.Default.ConnectionStringName = "New Connection String";
Properties.Settings.Default.Save();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM