簡體   English   中英

在VS2005中更改ConnectionString(C#)

[英]Change ConnectionString in VS2005 (C#)

我知道也有類似的問題

但是,問題仍然沒有答案! 我需要修改連接字符串而不添加新的。

這將幫助您!

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

對於更新而言,很難找到任何有用的代碼來更新連接字符串。 無法更新連接字符串,因此我刪除了連接字符串,並添加了一個新的字符串。 好吧,這不奇怪嗎? 微軟留下了一些未完成的內容...也許對您的app.config進行更改可能沒有用,但是無論如何,我不得不這么做。 因此動態的app.config或web.config文件有點奇怪,因為您無法動態更新它。 不,您必須先由configurationmanager刪除它。

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

這是一個古老的問題,我只想知道最終為您解決了什么解決方案。 如果尚未解決,則此問題將嘗試回答它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM