web-dev-qa-db-ja.com

ConfigurationManager.OpenExeConfiguration-間違ったファイルをロードしますか?

複数の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を使用して構成ファイルを正しくロードするにはどうすればよいですか?

34
user9659

http://social.msdn.Microsoft.com/Forums/en-US/winforms/thread/3943ec30-8be5-4f12-9667-3b812f711fc9 によると、パラメーターはexeの場所であり、メソッドは、そのexeに対応する構成を探します(exePathのパラメーター名は今では意味があると思います!)。

22
user9659

この解決策を見つけた場所を思い出せませんが、特定のexe構成ファイルをロードする方法を以下に示します。

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

この問題を完全に回避するには、次のように、構成ファイルを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;
8
Francis Huang
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を含む実行可能ファイルの名前です。

2
Ron Hagerman