C# 在运行时更改连接字符串并重新加载 app.config

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/502411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:51:59  来源:igfitidea点击:

Change connection string & reload app.config at run time

c#configuration

提问by

When I change the connection string using this code, it does not reload app.configat runtime. I expected it to reload similarly to how we reload app.config.

当我使用此代码更改连接字符串时,它不会app.config在运行时重新加载。我希望它重新加载类似于我们重新加载的方式app.config

config.ConnectionStrings.ConnectionStrings["JVVNL_NEW.Properties.Settings.JVVNL_NEWConnectionString1"].ConnectionString = ConString;
config.ConnectionStrings.ConnectionStrings["CMS_NEW.Properties.Settings.JVVNL_NEWConnectionString1"].ConnectionString = ConString;
config.Save(ConfigurationSaveMode.Modified,true);
ConfigurationManager.RefreshSection(config.ConnectionStrings.SectionInformation.SectionName);

回答by Cerebrus

IIRC, the ConfigurationManager.RefreshSection requires a string parameter specifying the name of the Section to refresh :

IIRC,ConfigurationManager.RefreshSection 需要一个字符串参数,指定要刷新的部分的名称:

ConfigurationManager.RefreshSection("connectionStrings");

I think that the ASP.NET application should automatically reload when the ConnectionStrings element is modified and the configuration does not need to be manually reloaded.

我认为 ASP.NET 应用程序应该在修改 ConnectionStrings 元素时自动重新加载并且不需要手动重新加载配置。

回答by ajma

Yeah, when ASP.NET web.config gets updated, the whole application gets restarted which means the web.config gets reloaded.

是的,当 ASP.NET web.config 更新时,整个应用程序会重新启动,这意味着 web.config 会重新加载。

回答by Neil Barnwell

You can also refresh the configuration in it's entirety:

您还可以完整地刷新配置:

ConnectionStringSettings importToConnectionString = currentConfiguration.ConnectionStrings.ConnectionStrings[newName];

if (importToConnectionString == null)
{
    importToConnectionString = new ConnectionStringSettings();
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
    importToConnectionString.Name = newName;
    currentConfiguration.ConnectionStrings.ConnectionStrings.Add(importToConnectionString);
}
else
{
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
}

Properties.Settings.Default.Reload();

回答by Bradley Mountford

Had to do this exact thing. This is the code that worked for me:

不得不做这件事。这是对我有用的代码:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["Blah"].ConnectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");

回答by Athanasios Kataras

First you might want to add

首先你可能想添加

using System.Configuration;

To your .cs file. If it not available add it through the Project References as it is not included by default in a new project.

到您的 .cs 文件。如果它不可用,请通过项目引用添加它,因为它默认不包含在新项目中。

This is my solution to this problem. First I made the ConnectionProperties Class that saves the items I need to change in the original connection string. The _name variable in the ConnectionProperties class is important to be the name of the connectionString The first method takes a connection string and changes the option you want with the new value.

这是我对这个问题的解决方案。首先,我创建了 ConnectionProperties 类,用于保存我需要在原始连接字符串中更改的项目。ConnectionProperties 类中的 _name 变量对于成为 connectionString 的名称很重要。第一种方法采用连接字符串并使用新值更改您想要的选项。

private String changeConnStringItem(string connString,string option, string value)
    {
        String[] conItems = connString.Split(';');
        String result = "";
        foreach (String item in conItems)
        {
            if (item.StartsWith(option))
            {
                result += option + "=" + value + ";";
            }
            else
            {
                result += item + ";";
            }
        }
        return result;
    }

You can change this method to accomodate your own needs. I have both mysql and mssql connections so I needed both of them. Of course you can refine this draft code for yourself.

您可以更改此方法以适应您自己的需要。我有 mysql 和 mssql 连接,所以我需要它们。当然,您可以自己细化此草稿代码。

private void changeConnectionSettings(ConnectionProperties cp)
{
     var cnSection = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     String connString = cnSection.ConnectionStrings.ConnectionStrings[cp.Name].ConnectionString;
     connString = changeConnStringItem(connString, "provider connection string=\"data source", cp.DataSource);
     connString = changeConnStringItem(connString, "provider connection string=\"server", cp.DataSource);
     connString = changeConnStringItem(connString, "user id", cp.Username);
     connString = changeConnStringItem(connString, "password", cp.Password);
     connString = changeConnStringItem(connString, "initial catalog", cp.InitCatalogue);
     connString = changeConnStringItem(connString, "database", cp.InitCatalogue);
           cnSection.ConnectionStrings.ConnectionStrings[cp.Name].ConnectionString = connString;
     cnSection.Save();
     ConfigurationManager.RefreshSection("connectionStrings");
}

As I didn't want to add trivial information I ommited the Properties region of my code. Please add it if you want this to work.

因为我不想添加琐碎的信息,所以我省略了代码的 Properties 区域。如果你想让它工作,请添加它。

class ConnectionProperties
{
    private String _name;
    private String _dataSource;
    private String _username;
    private String _password;
    private String _initCatalogue;

    /// <summary>
    /// Basic Connection Properties constructor
    /// </summary>
    public ConnectionProperties()
    {

    }

    /// <summary>
    /// Constructor with the needed settings
    /// </summary>
    /// <param name="name">The name identifier of the connection</param>
    /// <param name="dataSource">The url where we connect</param>
    /// <param name="username">Username for connection</param>
    /// <param name="password">Password for connection</param>
    /// <param name="initCat">Initial catalogue</param>
    public ConnectionProperties(String name,String dataSource, String username, String password, String initCat)
    {
        _name = name;
        _dataSource = dataSource;
        _username = username;
        _password = password;
        _initCatalogue = initCat;
    }
// Enter corresponding Properties here for access to private variables
}

回答by Joselo

//here is how to do it in Windows App.Config

//这里是如何在Windows App.Config中做到这一点

public static bool ChangeConnectionString(string Name, string value, string providerName, string AppName)
    {
        bool retVal = false;
        try
        {

            string FILE_NAME = string.Concat(Application.StartupPath, "\", AppName.Trim(), ".exe.Config"); //the application configuration file name
            XmlTextReader reader = new XmlTextReader(FILE_NAME);
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            reader.Close();
            string nodeRoute = string.Concat("connectionStrings/add");

            XmlNode cnnStr = null;
            XmlElement root = doc.DocumentElement;
            XmlNodeList Settings = root.SelectNodes(nodeRoute);

            for (int i = 0; i < Settings.Count; i++)
            {
                cnnStr = Settings[i];
                if (cnnStr.Attributes["name"].Value.Equals(Name))
                    break;
                cnnStr = null;
            }

            cnnStr.Attributes["connectionString"].Value = value;
            cnnStr.Attributes["providerName"].Value = providerName;
            doc.Save(FILE_NAME);
            retVal = true;
        }
        catch (Exception ex)
        {
            retVal = false;
            //Handle the Exception as you like
        }
        return retVal;
    }

回答by Romesh

//You can apply the logic in "Program.cs"

//Logic for getting new connection string
//****
//

MyDBName="mydb";

//
//****

//Assign new connection string to a variable
string newCnnStr = a="Data Source=.\SQLExpress;Initial Catalog=" + MyDBName + ";Persist Security Info=True;User ID=sa;Password=mypwd";

//And Finally replace the value of setting
Properties.Settings.Default["Nameof_ConnectionString_inSettingFile"] = newCnnStr;

//This method replaces the value at run time and also don't needs app.config for the same setting. It will have the va;ue till the application runs.

//It worked for me.