use*_*659 34 c# configurationmanager
我已将多个app.config(每个都有一个不同的名称)文件添加到项目中,并将它们设置为复制到每个构建的输出目录.
我尝试使用以下方法访问每个文件的内容:
System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(@"app1.config");
Run Code Online (Sandbox Code Playgroud)
代码运行,但o.HasFile结束False,o.FilePath结束"app1.config.config".如果我改为代码:
System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(@"app1");
Run Code Online (Sandbox Code Playgroud)
然后代码炸弹"加载配置文件时发生错误:参数'exePath'无效.参数名称:exePath".
如果我复制/粘贴配置文件(所以我最终使用app1.config和app1.config.config)然后代码运行正常,但是,我认为这不是一个好的解决方案.我的问题是:如何使用ConfigurationManager.OpenExeConfiguration正确加载配置文件?
小智 52
我不记得我在哪里找到了这个解决方案,但这里是我设法加载一个特定的exe配置文件:
ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = "EXECONFIG_PATH" };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
Run Code Online (Sandbox Code Playgroud)
use*_*659 22
根据 http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/3943ec30-8be5-4f12-9667-3b812f711fc9,参数是exe的位置,然后该方法查找配置对应于那个exe(我猜exePath的参数名称现在有意义!).
要完全避免此问题,您可以将配置文件作为XML文件读取,例如:
using System.Xml;
using System.Xml.XPath;
XmlDocument doc = new XmlDocument();
doc.Load(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\..\\..\\..\\MyWebProject\\web.config");
string value = doc.DocumentElement.SelectSingleNode("/configuration/appSettings/add[@key='MyKeyName']").Attributes["value"].Value;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53459 次 |
| 最近记录: |