ConfigurationManager.OpenExeConfiguration - 加载错误的文件?

时间:2009-07-05 11:55:42

标签: c# configurationmanager

我已将多个app.config(每个都有一个不同的名称)文件添加到项目中,并将它们设置为复制到每个构建的输出目录。

我尝试使用以下方法访问每个文件的内容:

System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(@"app1.config");

代码运行,但o.HasFile结束False,o.FilePath结束“app1.config.config”。如果我改为代码:

System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(@"app1");

然后代码炸弹“加载配置文件时出错:参数'exePath'无效。参数名称:exePath”。

如果我复制/粘贴配置文件(所以我最终使用app1.config和app1.config.config)然后代码运行正常,但是,我认为这不是一个好的解决方案。我的问题是:如何使用ConfigurationManager.OpenExeConfiguration正确加载配置文件?

4 个答案:

答案 0 :(得分:49)

我不记得我在哪里找到了这个解决方案,但这里是我如何设法加载特定的exe配置文件:

ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = "EXECONFIG_PATH" };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

答案 1 :(得分:22)

根据http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/3943ec30-8be5-4f12-9667-3b812f711fc9,参数是exe的位置,然后该方法查找与该exe相对应的配置(我想现在exePath的参数名称有意义了!)。

答案 2 :(得分:8)

要完全避免此问题,您可以将配置文件作为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;

答案 3 :(得分:2)

using System.Reflection;

try
{
    Uri UriAssemblyFolder = new Uri(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
    string appPath = UriAssemblyFolder.LocalPath;

    //Open the configuration file and retrieve 
    //the connectionStrings section.
    Configuration config = ConfigurationManager.
        OpenExeConfiguration(appPath + @"\" + exeConfigName);

    ConnectionStringsSection section =
        config.GetSection("connectionStrings")
        as ConnectionStringsSection;
}

至少,这是我在加密和解密我的控制台/ GUI应用程序的connectionStrings部分时使用的方法。 exeConfigName是可执行文件的名称,包括.exe。