场景:
在dll项目中新增了一个xxx.config文件,并使用config中配置的值;
问题:
dll项目使用了ConfigurationManager.Appsettings["xxx"]获取值,但打包dll项目并在其他项目中引用dll时,配置读取的是主项目的web.config
原因:
ConfigurationManager.Appsettings读取的是主项目根目录下的配置文件,如果想读取dll项目中的配置,需要用其他方法
解决:
在dll项目中,读取config配置,使用指定路径下的读取config配置方法:
private string GetConfigValue(string key)
{
string result = "";
string basePath = System.Web.HttpContext.Current.Server.MapPath("~/");
System.IO.DirectoryInfo pathInfo = new System.IO.DirectoryInfo(basePath);
string path =pathInfo.FullName + @"\bin\FlowControl.dll.config";//指定config文件名
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap() ;
configFileMap.ExeConfigFilename = path;
var config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap,ConfigurationUserLevel.None);
result = config.AppSettings.Settings[key].Value;//appSection.Settings[key].Key;
return result;
}
备注:
1 注意名称问题,否则会读取不到配置:dll项目中新增的是app.config,但是打包生成dll后,config会变成dllname.config;
2 引用dll时,注意要把config文件一起拷走