永不言弃!
不忘初心:感恩的心!上进的心!

工具:vs2019

winform中读取配置文件:appsettings.json

 

 appsettings.json文件内容如下:

{
  "ConnectionStrings": {
    "MySqlCon": "Data Source=localhost;Port=3306;Database=lgee_shop;User Id=root;Password=root;CharSet=utf8mb4;"
  }
}

 

配置文件设置为:始终复制

 

 

 

读取步骤

第一步:引入相关包

1.Microsoft.Extensions.Configuration;
2.Microsoft.Extensions.Configuration.Json;

 

 

 

第二部:创建读取配置类文件

创建类文件:CustomConfigManager

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace POSTrade
{
    public class CustomConfigManager
    {
        //读取配置文件:appsettings
        //1.Microsoft.Extensions.Configuration;
        //2.Microsoft.Extensions.Configuration.Json; 
        public static string GetConfig(string key)
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); //默认读取:当前运行目录
            IConfigurationRoot configuration = builder.Build();
            string configValue = configuration.GetSection(key).Value;
            return configValue;
        }
    }
}

 

第三步:读取数据

 //读取配置文件  
 string strCon = CustomConfigManager.GetConfig("ConnectionStrings:MySqlCon");

到此,配置文件的数据正常读取

 

posted on 2022-02-24 10:53  永不言弃!  阅读(2055)  评论(0编辑  收藏  举报