码迷,mamicode.com
首页 > Web开发 > 详细

config.json读取和存储

时间:2019-07-03 13:59:51      阅读:332      评论:0      收藏:0      [点我收藏+]

标签:存储   try   sharp   bsp   save   object   des   line   end   

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;
            }
        }
}

  

 

config.json读取和存储

标签:存储   try   sharp   bsp   save   object   des   line   end   

原文地址:https://www.cnblogs.com/yaosj/p/11125643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!