config.json读取和存储

json格式的配置文件的读取和存储

    public class ConfigHelper
    {
        public static T GetConfig<T>(string path)
        {
            if (string.IsNullOrEmpty(path))
                return default(T);

            try
            {
                string strConfig = FileHelper.ReadFromFile(path);
                if (string.IsNullOrEmpty(strConfig))
                    return default(T);

                return JsonConvert.DeserializeObject<T>(strConfig);

            }
            catch (Exception)
            {
                return default(T);
            }
        }

        public static bool SaveConfig<T>(string path, T t)
        {
            try
            {
                if (string.IsNullOrEmpty(path) || t == null)
                    return false;

                string strConfig = JsonConvert.SerializeObject(t);
                if (string.IsNullOrEmpty(strConfig))
                    return false;

                if (!FileHelper.WriteToFile(path, strConfig))
                    return false;

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
}

  

    public class FileHelper
    {
        public static string ReadFromFile(string path)
        {
            if (string.IsNullOrEmpty(path) || !File.Exists(path))
                return null;

            try
            {
                using (StreamReader reader = new StreamReader(path, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static bool WriteToFile(string path, string content)
        {
            if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(content))
                return false;

            try
            {
                using (StreamWriter writer = new StreamWriter(path, false, Encoding.UTF8))
                {
                    writer.WriteLine(content);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
}

  

 

转载于:https://www.cnblogs.com/yaosj/p/11125643.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值