Изменить ConnectionString в VS2005 (C #) - PullRequest
1 голос
/ 24 ноября 2008

Я знаю, что похожая проблема .

Но, тем не менее, на этот вопрос нет ответа! Мне нужно изменить строку подключения, а не добавить новую.

Ответы [ 2 ]

6 голосов
/ 24 ноября 2008

Это вам поможет!

        /// <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);       
        }

Ну, для обновления было трудно найти что-либо полезное код для обновления строки подключения. Это было невозможно обновить строку подключения, поэтому я должен был удалить Строка соединения, и добавьте новую. Ну разве это не странно? Microsoft оставила что-то недействительным ... Ну, может быть, это бесполезно чтобы изменить ваш 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);
        }
0 голосов
/ 30 июля 2009

Это старый вопрос, и я просто хотел бы знать, какое решение в конечном итоге сработало для вас. Если вы еще не решили, этот вопрос пытается ответить на него.

...