咱们在项目中通常都是使用统一的项目文件配置,全部的配置和自定义的字段都写在一个web.config或者App.config文件中。通常平时咱们也没有发现问题,确实这么写没有问题,可是就是若是写的多了就看着很臃肿。web
而且假如你其余地方不是主项目的配置也写在这里,多了是否是很乱,有时候本身都不知道这个是配置的那个东西了。这不我在搭建本身的框架作日志写入的时候就发现这个问题,我就想由于我日志写入我是单独做为类库存在的,因此我不必定非要写在web.config中啊。我直接写在我类库下的配置文件就能够啊。想法不错说干就干,通过一下午的鼓捣吧(其实也弄别的拉。)终于封装成了一个方法其实很简单,主要是总是报路径错误鼓捣的时间。本来我是想用程序集的路径(Assembly.Location或者assembly.CodeBase)不过研究半天发现他们给的路径都很差使,也不知道为何(回头再研究先解决眼下的问题)。反正是一个给返回C盘的路径一个是有多于字段。最后我仍是用AppDomain这个代替吧,先用着发现不行在撤。嘻嘻嘻app
最后大概就是这么一个结构:框架
类就是config的帮助扩展类,而后读取到的就是当前下的app.config。spa
方法代码:日志
1 #region 1.获取当前类库的文件配置 2 public static Configuration InitLogConfig() 3 { 4 string baesePath = AppDomain.CurrentDomain.RelativeSearchPath; 5 string fullName = Path.GetFileName(Assembly.GetCallingAssembly().Location); 6 string path = string.Format(@"{0}\{1}.config", baesePath, fullName); 7 if (File.Exists(path) == false) 8 { 9 string msg = string.Format("{0}路径下的文件未找到 ", path); 10 throw new FileNotFoundException(msg); 11 } 12 try 13 { 14 ExeConfigurationFileMap configFile = new ExeConfigurationFileMap(); 15 configFile.ExeConfigFilename = path; 16 Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None); 17 return config; 18 } 19 catch (Exception ex) { throw new Exception(ex.Message); 20 } 21 } 22 #endregion
config我如今就随便写了一个 appSettings来给你们演示一下:code
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="LogPath" value="E:\"/> </appSettings> </configuration>
下面就是为了演示写的调用:orm
而后是运行结果:咱们能够看到配置文件是E盘,全部咱们读取到的路径也是E盘xml
走到这里就说明方法成功了。我很开心哈哈。想法实现了。blog
注意:这个扩展是那个方法调用所在的项目或者类库的配置文件不是不变的。utf-8
写完这个以后我又想到一个想法那就是指定读取项目中类库的配置文件,有了第一个的基础,这个还不是手到擒来。全部代码就改为这样了:
1 #region 2.获取当前指定位置文件配置 2 public static Configuration InitLogConfig2(string fullName) 3 { 4 string baesePath = AppDomain.CurrentDomain.RelativeSearchPath; 5 6 string path = string.Format(@"{0}\{1}.dll.config", baesePath, fullName); 7 if (File.Exists(path) == false) 8 { 9 string msg = string.Format("{0}路径下的文件未找到 ", path); 10 throw new FileNotFoundException(msg); 11 } 12 try 13 { 14 ExeConfigurationFileMap configFile = new ExeConfigurationFileMap(); 15 configFile.ExeConfigFilename = path; 16 Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None); 17 return config; 18 } 19 catch (Exception ex) 20 { 21 throw new Exception(ex.Message); 22 } 23 24 }
为了演示我就这样子写一下吧,不演示一下在不明白区别:
运行起来效果:
能够看到一个是类库的E盘一个是我主文件写的D盘,说明成功了。