c#读取另外的配置文件

在使用自定义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;

            }

        }

    }

 

你可能感兴趣的:(配置文件)