37

我在一个项目中添加了多个 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

4 回答 4

61

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

ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = "EXECONFIG_PATH" };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
于 2012-09-25T16:21:03.170 回答
23

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

于 2009-07-05T12:17:17.600 回答
9

为了完全避免这个问题,您可以将配置文件作为 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;
于 2011-03-14T23:01:58.520 回答
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。

于 2012-01-30T16:23:04.767 回答