20

我有一個App.Config文件的exe文件。現在我想創建一個包裝DLL的exe文件,以消耗一些功能。獲取另一個exe的App.Config

問題是我如何從包裝DLL訪問exe中的app.config屬性?

也許我應該多一點點我的問題,我有以下的app.config內容與EXE:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <appSettings> 
    <add key="myKey" value="myValue"/> 
    </appSettings> 
</configuration> 

的問題是如何如何得到「myvalue的」出從包裝dll的?


感謝您的解決方案。

其實我最初的概念是爲了避免XML文件閱讀方法或LINQ或其他。我的首選解決方案是使用configuration manager libraries and the like

我會感謝任何使用通常與訪問app.config屬性相關的類的幫助。

回答

4

一些測試後,我發現了一個辦法做到這一點。

  1. 將App.Config文件添加到測試項目。使用「添加爲鏈接」選項。
  2. 使用​​來訪問該值。
+0

+1如果你還沒有發佈這個答案。對於一個解決方案中跨不同項目的配置文件,這也是一個很好的解決方案。 – takrl 2012-02-23 07:29:16

0

這是一個xml文件,您可以使用基於Linq-XML或DOM的方法來解析出相關信息。
(這說我會問,如果沒有更好的設計,無論它是什麼..你試圖實現。)

21

ConfigurationManager.OpenMappedExeConfiguration Method將允許你這樣做。從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); 
+0

嗨Espo, 你的建議是偉大的。但也許我正在尋找的是有點不同。我編輯我的問題是更加明確的。 – Graviton 2008-09-10 08:09:10

+0

我現在已經添加了一個如何輸出所需的鍵/值的示例。 – Espo 2008-09-10 19:22:33

0

我第二次Gishu的觀點,即有另一種方式。將EXE的common /「public」部分抽象成DLL創建一個包裝EXE來運行它不是更好嗎?這當然是更通常的發展模式。只有你想要消耗的東西會進入DLL,而EXE會完成它目前所做的所有事情,減去進入DLL的內容。

+0

你好,我意識到你在這裏有一個觀點。 但我創建封裝DLL作爲測試程序集來測試我的EXE內部的邏輯。所以我沒有選擇:) – Graviton 2008-09-10 07:28:26

2

我想你要找的是什麼:

System.Configuration.ConfigurationManager.OpenExeConfiguration(string path) 
-1

在IDE中添加鏈接只會在開發過程中提供幫助。我認爲lomaxx有正確的想法:System.Configuration.ConfigurationManager.OpenExeConfiguration.