我知道这个问题很久以前就被贴出来了,但我希望这个答案仍然有用。
似乎没有标准的方法可以做到这一点。然而,通过访问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>();
}
“appSettings”部分也被加载了,因为我必须访问它才能使它一致地工作。