【Config】类库读取自己的配置文件,配置文件的扩展

    我们在项目中一般都是使用统一的项目文件配置,所有的配置和自定义的字段都写在一个web.config或者App.config文件中。一般平时我们也没有发现问题,确实这么写没有问题,但是就是如果写的多了就看着很臃肿。

并且假如你其他地方不是主项目的配置也写在这里,多了是不是很乱,有时候自己都不知道这个是配置的那个东西了。这不我在搭建自己的框架做日志写入的时候就发现这个问题,我就想因为我日志写入我是单独作为类库存在的,所以我不一定非要写在web.config中啊。我直接写在我类库下的配置文件就可以啊。想法不错说干就干,经过一下午的鼓捣吧(其实也弄别的拉。)终于封装成了一个方法其实很简单,主要是老是报路径错误鼓捣的时间。原本我是想用程序集的路径(Assembly.Location或者assembly.CodeBase)不过研究半天发现他们给的路径都不好使,也不知道为什么(回头再研究先解决眼下的问题)。反正是一个给返回C盘的路径一个是有多于字段。最后我还是用AppDomain这个代替吧,先用着发现不行在撤。嘻嘻嘻

最后大概就是这么一个结构:

类就是config的帮助扩展类,然后读取到的就是当前下的app.config。

方法代码:

 1         #region 1.获取当前类库的文件配置
 2         public static Configuration InitLogConfig()
 3         {
 4             Assembly assembly = Assembly.GetExecutingAssembly();
 5             string cc = assembly.CodeBase;
 6             string baesePath = AppDomain.CurrentDomain.RelativeSearchPath;
 7             string fullName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
 8             string path = string.Format(@"{0}\{1}.config", baesePath, fullName);
 9             if (File.Exists(path) == false)
10             {
11                 string msg = string.Format("{0}路径下的文件未找到 ", path);
12                 throw new FileNotFoundException(msg);
13             }
14             try
15             {
16                 ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
17                 configFile.ExeConfigFilename = path;
18                 Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
19                 return config;
20             }
21             catch (Exception ex) { throw new Exception(ex.Message);
22             }
23         }
24         #endregion

config我现在就随便写了一个 appSettings来给大家演示一下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="LogPath" value="E:\"/>
  </appSettings>
</configuration>

下面就是为了演示写的调用:

然后是运行结果:我们可以看到配置文件是E盘,所有我们读取到的路径也是E盘

 走到这里就说明方法成功了。我很开心哈哈。想法实现了。

猜你喜欢

转载自www.cnblogs.com/yanbigfeg/p/9714144.html