我知道這個問題被張貼在很久以前,但我希望這個答案仍然是有用的。
似乎有這樣做的標準方法。但是,通過訪問ConfigurationManager類的內部字段和類型,我可以列出所有加載的部分。這是我做的:
private static IEnumerable<string> GetLoadedSections()
{
// s_configSystem can be null if the ConfigurationManager is not properly loaded. Accessing the AppSettings *should* do the trick.
var appSettings = ConfigurationManager.AppSettings;
FieldInfo s_configSystemField = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static);
object s_configSystem = s_configSystemField.GetValue(null);
FieldInfo _completeConfigRecordField = s_configSystem.GetType().GetField("_completeConfigRecord", BindingFlags.NonPublic | BindingFlags.Instance);
object _completeConfigRecord = _completeConfigRecordField.GetValue(s_configSystem);
FieldInfo _sectionRecordsField = _completeConfigRecord.GetType().GetField("_sectionRecords", BindingFlags.NonPublic | BindingFlags.Instance);
Hashtable _sectionRecords = (Hashtable)_sectionRecordsField.GetValue(_completeConfigRecord);
return _sectionRecords.Keys.OfType<string>();
}
的「System.Diagnostics程序」部分,似乎總是被加載。 「appSettings」部分也被加載,因爲我必須訪問它才能使其始終如一地工作。
這適用於我的機器(.NET 4.5),但由於它依賴於內部的東西,如果Microsoft決定更改ConfigurationManager類的實現,它可以在任何時候中斷。