在使用自訂configsection時,涉及到讀取非預設的web.config 或者app.config。會用到下面的類。
public sealed class ImportConfig { private static string GetAssemblyPath() { string assemblypath = Assembly.GetExecutingAssembly().CodeBase; assemblypath = assemblypath.Substring(8, assemblypath.Length - 8); assemblypath = Path.GetDirectoryName(assemblypath); return assemblypath; } static ImportConfig() { var path =GetAssemblyPath()+ @"\config\import.config"; var file = new FileInfo(path); if (file.Exists) { var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = path }; _config = (ImportSection)ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None).GetSection("import"); } else { throw new FileNotFoundException(path); } } private static ImportSection _config; public static ImportSection Config { get { return _config; } } }