1_C#实现读写app.config中的connectionStrings和Web.config里的connectionStrings

1、读写app.config中的connectionStrings

要添加配置文件的引用才能读取哦

对app.configjin进行读(获取ConnectionStrings)

string connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;

在程序中对app.configjin的ConnectionStrings进行更新的方法

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

然后在调用这个方法即可:

//读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");

appconfig里配置如下:
非本地访问可以写Source=.,也就是有网才能写.

<connectionStrings>
		<add name="ConStr" connectionString="Data Source=127.0.0.1;database=Demo;uid=sa;pwd=123456"/>
	</connectionStrings>


2、读写Web.config中的connectionStrings

两种获取connectionString的方式:

public static string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
Web.config中的配置字符串为:

<connectionStrings>  
<add name="ConnectionString" connectionString="Data Source=localhost;Persist Security Info=True;User ID=***;Password=***;Unicode=True"  

  providerName="System.Data.OracleClient" />  

</connectionStrings> 

public static string connectionString = ConfigurationSettings.AppSettings["ConnectionString"];

Web.config中的配置字符串为:

<add key="ConnectionString" value="server=localhost;database=***;uid=sa;pwd=***"></add> 
posted @ 2021-11-07 12:26  青仙  阅读(1172)  评论(0编辑  收藏  举报