Get the App.Config of another Exe

两盒软妹~` 提交于 2019-11-28 23:02:04
Espo

The ConfigurationManager.OpenMappedExeConfiguration Method will allow you to do this.

Sample from the MSDN page:

static void GetMappedExeConfigurationSections()
{
    // Get the machine.config file.
    ExeConfigurationFileMap fileMap =
        new ExeConfigurationFileMap();
    // You may want to map to your own exe.comfig file here.
    fileMap.ExeConfigFilename = 
        @"C:\test\ConfigurationManager.exe.config";
    System.Configuration.Configuration config =
        ConfigurationManager.OpenMappedExeConfiguration(fileMap, 
        ConfigurationUserLevel.None);

    // Loop to get the sections. Display basic information.
    Console.WriteLine("Name, Allow Definition");
    int i = 0;
    foreach (ConfigurationSection section in config.Sections)
    {
        Console.WriteLine(
            section.SectionInformation.Name + "\t" +
        section.SectionInformation.AllowExeDefinition);
        i += 1;

    }
    Console.WriteLine("[Total number of sections: {0}]", i);

    // Display machine.config path.
    Console.WriteLine("[File path: {0}]", config.FilePath);
}

EDIT: This should output the "myKey" value:

ExeConfigurationFileMap fileMap =
    new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = 
    @"C:\test\ConfigurationManager.exe.config";
System.Configuration.Configuration config =
    ConfigurationManager.OpenMappedExeConfiguration(fileMap, 
    ConfigurationUserLevel.None);
Console.WriteLine(config.AppSettings.Settings["MyKey"].Value);

After some testing, I found a way to do this.

  1. Add the App.Config file to the test project. Use "Add as a link" option.
  2. Use System.Configuration.ConfigurationManager.AppSettings["myKey"] to access the value.
lomaxx

I think what you're looking for is:

System.Configuration.ConfigurationManager.OpenExeConfiguration(string path)

I'd second Gishu's point that there's another way. Wouldn't it be better to abstact the common/"public" part of the EXE out into DLL create a wrapper EXE to run it? This is certainly the more usual pattern of development. Only the stuff that you wish to consume would go into the DLL, and the EXE would do all the stuff it currently does, minus what's gone into the DLL.

It's an xml file, you can use Linq-XML or DOM based approaches to parse out the relevant information.
(that said I'd question if there isn't a better design for whatever it is.. you're trying to achieve.)

tkrehbiel

Adding a link in the IDE would only help during development. I think lomaxx has the right idea: System.Configuration.ConfigurationManager.OpenExeConfiguration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!