zoukankan      html  css  js  c++  java
  • 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;
                }
            }
    }
    

      

  • 相关阅读:
    art.dialog
    Asp.net中web.config配置文件详解
    Web.Config文件配置之限制上传文件大小和时间
    Asp.net中的一个判断session是否合法的做法
    js倒计时
    Asp.net中web.config配置文件详解
    C#调用耗时函数时显示进度条浅探
    ChannelFactory
    NetTcpBinding 类nettcpbinding的属性和方法
    n!的位数 斯特林公式
  • 原文地址:https://www.cnblogs.com/yaosj/p/11125643.html
Copyright © 2011-2022 走看看