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

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM