标签:
想要通过配置文件配置C#前台画面,好奇做了以下测试:在项目中新建了app.config与app1.config两个配置文件,
请教一下各位高手如果想从app1.config中读取配置信息应该如何读取?
采用ConfigurationManager.AppSettings 属性似乎只能读取到app.config的配置信息。
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = @"D:\App1.config";// 这里对应你app1文件的路径
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
string connstr = config.ConnectionStrings.ConnectionStrings["connStr"].ConnectionString;
MessageBox.Show(connstr);
string key = config.AppSettings.Settings["key"].Value;
MessageBox.Show(key);
using System; using System.Configuration; namespace JADAY.Frame.Common { public class ConfigHelper { /// <summary> /// 获取webconfig指定键的值 /// </summary> /// <param name="key">指定键</param> /// <param name="defaultValue">当获取的值为空时返回该值</param> /// <returns></returns> public static string GetAppSettings(string key, string defaultValue = "") { var value = ConfigurationManager.AppSettings[key];//获取指定的配置信息 return value == null ? defaultValue : value.ToStringValue(); } /// <summary> /// 获取webconfig指定键的值 /// </summary> /// <param name="name">指定名称</param> /// <param name="defaultValue">当获取的值为空时返回该值</param> /// <returns></returns> public static string GetConnectionString(string name, string defaultValue = "") { //获取指定的配置信息 var value = ConfigurationManager.ConnectionStrings[name].ConnectionString; return value == null ? defaultValue : value.ToStringValue(); } /// <summary> /// 获取App_Data中配置文件指定键的值 /// </summary> /// <param name="key">键</param> /// <param name="defaultValue">默认值</param> /// <returns></returns> public static string GetAppDataAppSettings(string key, string defaultValue = "") { var map = new ExeConfigurationFileMap { ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\App.config" }; var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); var value = config.AppSettings.Settings[key].Value; return value == null ? defaultValue : value.ToStringValue(); } /// <summary> /// 获取App_Data中数据连接字符串 /// </summary> /// <param name="name">数据连接名字</param> /// <param name="defaultValue">默认值</param> /// <returns></returns> public static string GetAppDataConnectionString(string name, string defaultValue = "") { var map = new ExeConfigurationFileMap { ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\App.config" }; var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); var value = config.ConnectionStrings.ConnectionStrings[name].ConnectionString; return value == null ? defaultValue : value.ToStringValue(); } } }
项目文件中含有两个config文件,app.config与app1.config,如何获取app1.config中的配置
标签:
原文地址:http://www.cnblogs.com/jaday/p/4212107.html