C#自定义的配置文件,配置值支持特殊符号

读取配置文件工具类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ITExplode.Common
{
    
    
    public static class MyConfigReader
    {
    
    
        private static readonly string configContent = null;

        static MyConfigReader()
        {
    
    
            //读取自定义配置文件 sysData.ini
            string fileConfig = AppDomain.CurrentDomain.BaseDirectory + "\\sysData.ini";
            configContent = System.IO.File.ReadAllText(fileConfig);

            //移除#开头的所有行, 去掉注释行
            Regex regular = new Regex("^\\s*#\\s*.*", RegexOptions.Multiline);
            configContent = regular.Replace(configContent, "");

            //移除空白行
            Regex regular2 = new Regex("^\\s*", RegexOptions.Multiline);
            configContent = regular2.Replace(configContent, "");
        }

        /// <summary>
        /// 读取配置文件sysData.ini节点的值
        /// </summary>
        /// <param name="configName">节点名称</param>
        /// <returns>返回节点值</returns>
        public static string GetConfigValue(string configName)
        {
    
    
            //解析配置
            Regex regular3 = new Regex($"\\s*({configName})\\s+.*");
            string nodeValue = regular3.Match(configContent).Value;

            //获取值移除空格
            Regex regex4 = new Regex(configName, RegexOptions.IgnoreCase);
            nodeValue = regex4.Replace(nodeValue, "");
            return nodeValue.Trim();
        }

    }
}

配置文件:
配置文件中,#开头的为注释
注释必须单独一行,不可以和配置值在一行混用
变量名不区分大小写,配置项格式:
变量名称+空格+配置值

sysData.ini配置文件参考

#验证密码的正则表达式,密码要求必须包含数字,字母,特殊符号,长度八位到50位以上
#password_check  ^(?=.*[a-zA-Z])(?=.*\d)(?=.*[?~!,\.#&@$%()|{}"<>'\+\*\-:;^_`])[a-zA-Z\d[?~!,\.#&@$%()|{}"<>'\+\*\-:;^_`]{8,}$
password_check  (?=.*[0-9])(?=.*[a-zA-Z])(?=([\x21-\x7e]+)[^a-zA-Z0-9]).{
    
    8,50}$

# 党建制度系统前端地址
AD_address  http://10.22.33.66:8090

#  SOA验证登录页面http://www.baidu.com
soa_loginpage  http://www.baidu.com


调用

            string password_check2 = ITExplode.Common.MyConfigReader.GetConfigValue("password_check");
            string AD_address2 = ITExplode.Common.MyConfigReader.GetConfigValue("AD_address");
            string soa_loginpage2 = ITExplode.Common.MyConfigReader.GetConfigValue("soa_loginpage");

猜你喜欢

转载自blog.csdn.net/u011511086/article/details/110928914