C# 采用自定义方式读取自定义配置文件App.config
需要使用App.config中的配置项,需要引用:
System.Configuration
C/C++ Code复制内容到剪贴板
- public class ConfigurationHelper
- {
- /// <summary>
- /// 打开默认配置文件中制定的Section;
- /// </summary>
- public static object GetSection(string sectionName)
- {
- return GetConfiguration().GetSection(sectionName);
- }
- public static ConnectionStringSettingsCollection ConnectionStrings
- {
- get { return GetConfiguration().ConnectionStrings.ConnectionStrings; }
- }
- public static KeyValueConfigurationCollection AppSettings
- {
- get { return GetConfiguration().AppSettings.Settings; }
- }
- /// <summary>
- /// 打开默认的配置文件;
- /// </summary>
- public static Configuration GetConfiguration()
- {
- string configFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Connection.config");
- return GetConfiguration(configFile);
- }
- /// <summary>
- /// 打开指定的配置文件;
- /// </summary>
- public static Configuration GetConfiguration(string configFile)
- {
- ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
- fileMap.ExeConfigFilename = configFile;
- return ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
- }
- }
C/C++ Code复制内容到剪贴板
- // 1、获取
- string ServiceUri = ConfigurationHelper.GetValue("ServiceUri");
- string db = ConfigurationHelper.GetValue("DataBase");
- string user = ConfigurationHelper.GetValue("DataBaseUser");
- string password = ConfigurationHelper.GetValue("DataBasePassword");
- // 2、添加
- ConfigurationHelper.SetValue("DataBase", ServiceUriBox.Text);