获取另一个Exe的App.Config
-
09-06-2019 - |
题
我有一个带有 App.Config
文件。现在我想围绕 exe 创建一个包装 dll,以便使用一些功能。
问题是如何从包装器 dll 访问 exe 中的 app.config 属性?
也许我应该多问一些问题,我的 exe 中有以下 app.config 内容:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="myKey" value="myValue"/>
</appSettings>
</configuration>
问题是如何从包装器 dll 中获取“myValue”?
感谢您的解决方案。
实际上我最初的想法是避免使用 XML 文件读取方法或 LINQ 或其他方法。我首选的解决方案是使用 配置管理器库等.
对于使用通常与访问 app.config 属性相关的类的任何帮助,我将不胜感激。
解决方案 2
经过一些测试,我找到了一种方法来做到这一点。
- 将App.Config文件添加到测试项目中。使用“添加为链接”选项。
- 使用
System.Configuration.ConfigurationManager.AppSettings["myKey"]
来访问该值。
其他提示
这 ConfigurationManager.OpenMappedExeConfiguration 方法 将允许你这样做。
来自 MSDN 页面的示例:
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);
}
编辑:这应该输出“myKey”值:
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);
我认为您正在寻找的是:
System.Configuration.ConfigurationManager.OpenExeConfiguration(string path)
我赞同 Gishu 的观点,即还有另一种方法。将 EXE 的公共/“公共”部分抽象到 DLL 中创建一个包装器 EXE 来运行它不是更好吗?这当然是更常见的发展模式。只有您希望使用的内容才会进入 DLL,而 EXE 将执行其当前执行的所有内容,减去进入 DLL 的内容。
它是一个 xml 文件,您可以使用 Linq-XML 或基于 DOM 的方法来解析出相关信息。
(这就是说我会质疑是否没有更好的设计。你正在努力实现目标。)
在 IDE 中添加链接只会在开发过程中有所帮助。我认为 lomaxx 的想法是正确的: System.Configuration.ConfigurationManager.OpenExeConfiguration.
不隶属于 StackOverflow