ConfigurationManager.OpenExeConfiguration - loads the wrong file?

后端 未结 4 882
旧巷少年郎
旧巷少年郎 2020-12-01 13:42

I have added multiple app.config (each with a differet name) files to a project, and set them to copy to the output directory on each build.

I try and access the con

相关标签:
4条回答
  • 2020-12-01 14:17

    I can't remember where I found this solution but here is how I managed to load a specific exe configuration file:

    ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = "EXECONFIG_PATH" };
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
    
    0 讨论(0)
  • 2020-12-01 14:20

    According to http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/3943ec30-8be5-4f12-9667-3b812f711fc9 the parameter is the location of an exe, and the method then looks for the config corresponding to that exe (I guess the parameter name of exePath makes sense now!).

    0 讨论(0)
  • 2020-12-01 14:23

    To avoid this problem altogether, you can read in the config file as an XML file, for example:

    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;
    
    0 讨论(0)
  • 2020-12-01 14:36
    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;
    }
    

    At least, this is the method I use when encrypting and decrypting the connectionStrings section for my console/GUI apps. exeConfigName is the name of the executable including the .exe.

    0 讨论(0)
提交回复
热议问题