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

时间:2009-02-02 07:07:54

标签: c# configuration

当我使用此代码更改连接字符串时,它不会在运行时重新加载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);

8 个答案:

答案 0 :(得分:80)

必须做到这一点。这是对我有用的代码:

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

答案 1 :(得分:6)

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

ConfigurationManager.RefreshSection("connectionStrings");

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

答案 2 :(得分:4)

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

答案 3 :(得分:2)

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

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

答案 4 :(得分:1)

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

答案 5 :(得分:1)

首先,您可能想要添加

using System.Configuration;

到你的.cs文件。如果不可用,请通过项目参考添加它,因为默认情况下它不包含在新项目中。

这是我解决这个问题的方法。 首先,我创建了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;
    }

您可以更改此方法以满足您自己的需求。我有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");
}

由于我不想添加琐碎的信息,我省略了代码的属性区域。如果您希望这样做,请添加它。

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
}

答案 6 :(得分:0)

//这里是如何在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;
    }

答案 7 :(得分:0)

这是我使用的方法:

public void AddOrUpdateAppConnectionStrings(string key, string value)
{
    try
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.ConnectionStrings.ConnectionStrings;
        if (settings[key] == null)
        {
            settings.Add(new ConnectionStringSettings(key,value));
        }
        else
        {
            settings[key].ConnectionString = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.ConnectionStrings.SectionInformation.Name);
        Properties.Settings.Default.Reload();
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}