1 using Newtonsoft.Json; 2 using System; 3 using System.Collections.Generic; 4 using System.IO; 5 using System.Linq; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace ConfigHandler 10 { 11 public class ConfigHandler<T> 12 where T : class 13 { 14 const string SAVE_PATH = "jsonconfig/"; 15 /// <summary> 16 /// 單例模式 17 /// </summary> 18 static T config; 19 private ConfigHandler() 20 { 21 22 } 23 /// <summary> 24 /// 獲取保存地址,默認是泛型參數T的類型名稱 25 /// </summary> 26 /// <returns></returns> 27 private static string GetSavePath() 28 { 29 if (!Directory.Exists(SAVE_PATH)) 30 { 31 Directory.CreateDirectory(SAVE_PATH); 32 } 33 return $"{SAVE_PATH}{typeof(T).ToString()}.json"; 34 } 35 /// <summary> 36 /// 保存配置 37 /// </summary> 38 public static void Save(T _config) 39 { 40 config = _config; 41 string json = JsonConvert.SerializeObject(_config); 42 try 43 { 44 using (var sw = new StreamWriter(GetSavePath())) 45 { 46 sw.WriteAsync(json); 47 } 48 49 } 50 catch (Exception) 51 { 52 throw; 53 } 54 } 55 /// <summary> 56 /// 獲取配置信息 57 /// </summary> 58 /// <returns></returns> 59 public static T Load() 60 { 61 if (config == null) 62 { 63 string json = ""; 64 try 65 { 66 using (var sr = new StreamReader(GetSavePath())) 67 { 68 json = sr.ReadToEnd(); 69 if (json != "") 70 { 71 config = JsonConvert.DeserializeObject<T>(json); 72 } 73 else 74 { 75 config = null; 76 } 77 } 78 } 79 catch (Exception) 80 { 81 config = null; 82 } 83 } 84 return config; 85 } 86 87 } 88 89 90 }View Code
demo:
using ConfigHandler; using ConsoleApplication1; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { MyConfig config = new MyConfig(); config = new MyConfig(); config.name = "leiming"; config.Age = 20; config.Time = DateTime.Now; ConfigHandler<MyConfig>.Save(config); config = ConfigHandler<MyConfig>.Load(); Console.WriteLine(config.ToString()); Console.ReadKey(); } } class MyConfig { public int Hello{get;set;} public string name { get; set; } public int Age { get; set; } public DateTime Time { get; set; } public override string ToString() { return $"Name={name},Age={Age},Time={Time.ToShortDateString()}"; } } }View Code