Change connection string & reload app.config at run time

前端 未结 8 1390
广开言路
广开言路 2020-11-28 03:26

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

相关标签:
8条回答
  • 2020-11-28 03:49

    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");
    
    0 讨论(0)
  • 2020-11-28 03:49
    //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.
    
    0 讨论(0)
  • 2020-11-28 03:50

    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();
    
    0 讨论(0)
  • 2020-11-28 03:55

    //here is how to do it in 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;
        }
    
    0 讨论(0)
  • 2020-11-28 03:57

    Here's the method I use:

    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");
        }
    }
    
    0 讨论(0)
  • 2020-11-28 03:59

    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.

    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.

    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.

    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.

    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
    }
    
    0 讨论(0)
提交回复
热议问题