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

  

 

posted @ 2019-07-03 12:02  翻白眼的哈士奇  阅读(2616)  评论(0编辑  收藏  举报