在VS2005中更改ConnectionString(C#)

时间:2008-11-24 12:40:13

标签: c# visual-studio-2005

我知道有some similar issue

但是,仍然没有回答这个问题!我需要修改连接字符串而不是添加新字符串。

2 个答案:

答案 0 :(得分:6)

这会帮助你!

        /// <summary>
        /// Add a connection string to the connection
        /// strings section and store it in the
        /// configuration file. 
        /// </summary>
        /// <param name="csName">The name of the property.</param>
        /// <param name="connectionString">The connectionstring as specified.</param>
        public static void AddConnectionStrings(string csName, string connectionString)
        {

            // Get the configuration file.
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

            // Add the connection string.
            ConnectionStringsSection csSection = config.ConnectionStrings;
            csSection.ConnectionStrings.Add(
                new ConnectionStringSettings(csName,
                    connectionString, "System.Data.SqlClient"));

            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Full);       
        }

好的更新很难找到任何有用的东西 用于更新连接字符串的代码。这是不可能的 更新一个连接字符串,所以我删除了 connectionstring,并添加一个新的。那不是很奇怪? 微软留下了一些东西...好吧也许它没用 改变你的app.config,但是,无论如何我必须做到。 所以动态的app.config或web.config文件有点奇怪,因为你无法动态更新它。不,你必须先通过配置管理器将其删除。

        /// <summary>
        /// First remove the old connectionstring and after that
        /// add a connection string to the connectionstrings
        /// section and store it in the configuration file. 
        /// </summary>
        /// <param name="csName">The name of the property.</param>
        /// <param name="connectionString">The connectionstring as specified.</param>
        public static void UpdateConnectionStrings(string csName, string connectionString)
        {
            // Get the configuration file
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

            // Remove the existing connectionstring.
            config.ConnectionStrings.ConnectionStrings.Remove(csName);
            // Add the connectionstring
            ConnectionStringsSection csSection = config.ConnectionStrings;
            csSection.ConnectionStrings.Add(
                new ConnectionStringSettings(csName, 
                connectionString, "System.Data.SqlClient"));

            // Save the configuration file
            config.Save(ConfigurationSaveMode.Full);
        }

答案 1 :(得分:0)

这是一个古老的问题,我想知道最终为您解决的解决方案。如果你还没有解决,this question会尝试回答它。