Winform中C#实现读写app.config中的connectionStrings

时间:2022-09-04 19:23:45

      由于在winform设计中,常常对datagridview利用向导设置数据源,那么在向导中的数据库连接字符串保存在app.config中。因此,如果涉及到修改数据库连接设置的时候,必须对app.config中的connectionStrings进行读写。

1. 对app.configjin进行读写的类ModifyAppConfig
class ModifyAppConfig
    {
        ///
        /// 获取ConnectionStrings
        ///
        ///
        ///
        public  string GetConnectionStringsConfig(string connectionName)
        {
            string connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
            return connectionString;
        }

        ///
        /// 更新连接字符串
        ///
        ///
        ///
        ///
        public  void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)
        {
            bool isModified = false;    //记录该连接串是否已经存在
            if (ConfigurationManager.ConnectionStrings[newName] != null)
            {
                isModified = true;
            }
            //新建一个连接字符串实例
            ConnectionStringSettings mySettings = new ConnectionStringSettings(newName, newConString, newProviderName);

            // 打开可执行的配置文件*.exe.config
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // 如果连接串已存在,首先删除它
            if (isModified)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
                // 将新的连接串添加到配置文件中.
                config.ConnectionStrings.ConnectionStrings.Add(mySettings);
                // 保存对配置文件所作的更改
                config.Save(ConfigurationSaveMode.Modified);
                // 强制重新载入配置文件的ConnectionStrings配置节 
                ConfigurationManager.RefreshSection("ConnectionStrings"); 
            }
        }
    }

2. 在程序中对app.config进行更新,代码如下:
//读app.config中的connectionStrings
ModifyAppConfig mac = new ModifyAppConfig();
string strConnStrings=mac.GetConnectionStringsConfig();
//重写app.config中的connectionStrings
ModifyAppConfig mac = new ModifyAppConfig();
mac.UpdateConnectionStringsConfig("brcc.Properties.Settings.brccConnectionString", strConn, "System.Data.SqlClient");

      至此,完成了对app.config中connectionStrings的读写操作。详细的对app.config进行读写操作,可参考下文:http://yueqing.blog.163.com/blog/static/32082592009813111946229/

http://cache.baidu.com/c?m=9d78d513d99256af59fa940f5e549571182497634bc0d1652e89cf1cc8314c41367192bc30551613a5c16b1600b8492dbbad6a2e605266ecc694c90c9de0ce7d6e9c60742e13dc0754910eaeb85b389777d40db7f25bb0fae732e4a9d182990944ca245427dfedd81a4609ca6df21f33e9bb9a4e115e12bbfa3012a51f28&p=983fc54ad7c905f20be291225b5f&user=baidu