在VS2005中更改ConnectionString(C#)

1 c# visual-studio-2005

我知道有一些类似的问题.

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

小智 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);       
        }
Run Code Online (Sandbox Code Playgroud)

好了更新,很难找到任何有用的代码来更新连接字符串.无法更新连接字符串,因此我删除了连接字符串,并添加了一个新连接字符串.那不是很奇怪?微软留下了一些东西...好吧也许改变你的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);
        }
Run Code Online (Sandbox Code Playgroud)