2009-07-05 42 views
30

我已經將多個app.config(每個都有一個不同的名稱)文件添加到項目中,並將它們設置爲複製到每個構建的輸出目錄。ConfigurationManager.OpenExeConfiguration - 加載錯誤的文件?

我試着訪問每個文件的使用該內容:

System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(@"app1.config"); 

的代碼運行,但o.HasFile結束了假,並o.FilePath結束了「app1.config.config」。如果我改變代碼:

System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(@"app1"); 

然後用代碼炸彈「發生錯誤加載配置文件:參數‘exePath’是無效參數名稱:exePath」。

如果我複製/粘貼配置文件(所以我最終與app1.config和app1.config.config)然後代碼運行良好,但是,我認爲這不是一個好的解決方案。我的問題是:我如何使用ConfigurationManager.OpenExeConfiguration來正確加載配置文件?

回答

21

根據http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/3943ec30-8be5-4f12-9667-3b812f711fc9該參數是一個exe的位置,然後該方法查找相應的配置文件的exe(我猜exePath的參數名稱現在有意義!)。

+4

注意,您可以通過任何路徑組件,而不僅僅是一個exe。所以你給「SomeLib.dll」,它會打開「SomeLib.dll.config」。 當你的.NET項目實際上只是一個你不想在其可執行文件旁邊部署一個.config的應用程序的插件時,它很有用。 – Ludovic 2010-04-09 17:55:27

+0

然而,當我把一個名爲app.config的文件放在dll的目錄中時,使用「app」作爲exePath參數,我必須在文件名改變之前將它改爲app ... – tobbenb3 2014-03-05 12:18:57

7

要完全避免這個問題,你可以在配置文件作爲一個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; 
+0

感謝XPath辦法。我已經使用ConfigurationManager約兩天了,Configuration.AppSettings.Settings.Count = 0.你的方法至少爲我設置了正確的值。 – TamusJRoyce 2011-09-19 13:38:45

2
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; 
} 

至少,這是加密和解密的ConnectionStrings當我使用的方法部分爲我的控制檯/ GUI應用程序。 exeConfigName是包含.exe的可執行文件的名稱。

44

我不記得在那裏我發現這個解決辦法,但這裏是我如何成功地加載特定的exe的配置文件:

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