how to change to connection string in web.config d

2019-02-17 20:19发布

问题:

I defind the connection string in 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#

回答1:

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".

Here is a trick using reflection to reset readOnly attribute of configuration element. See this article for full details Programmatically setting a connectionString property

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.



回答2:

You can open your Web.Config file for reading and writing using WebConfigurationManager.OpenWebConfiguration or WebConfigurationManager.OpenMappedWebConfiguration. 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.

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();
}


回答3:

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.

You should check out a User Scoped value in a Settings file instead.

MSDN - Using Settings in C

When using settings like this, changing the value at runtime is easy:

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


回答4:

Use 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();
}


回答5:

in Web Confige put this code

<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");


标签: c# web-config