C # saving generic classes with json for Object Instantiation can easily save program settings,

Source: Internet
Author: User

C # saving generic classes with json for Object Instantiation can easily save program settings,

Reference page:

Http://www.yuanjiaocheng.net/webapi/test-webapi.html

Http://www.yuanjiaocheng.net/webapi/web-api-controller.html

Http://www.yuanjiaocheng.net/webapi/config-webapi.html

Http://www.yuanjiaocheng.net/webapi/web-api-route.html

Http://www.yuanjiaocheng.net/webapi/parameter-binding.html

It is used for permanent objects. Any program can be used and it depends on NewtonSoft. Used for json serialization and deserialization.
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 ConfigHandler10 {11 public class ConfigHandler <T> 12 where T: class13 {14 const string SAVE_PATH = "jsonconfig /"; 15 /// <summary> 16 // Singleton mode 17 /// </summary> 18 static T config; 19 private ConfigHandler () 20 {21 22} 23/ // <Summary> 24 // get the Save address, the default type is generic parameter T. The type name is 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 // Save configuration 37 // </summary> 38 public static void Save (T _ config) 39 {40 config = _ config; 41 string json = JsonConvert. serializeObject (_ config); 42 try43 {44 using (var sw = new StreamWriter (GetSavePath () 45 {46 sw. writeAsync (json); 47} 48 49} 50 catch (E Xception) 51 {52 throw; 53} 54} 55 // <summary> 56 // obtain configuration information 57 // </summary> 58 // <returns> </returns> 59 public static T Load () 60 {61 if (config = null) 62 {63 string json = ""; 64 try65 {66 using (var sr = new StreamReader (GetSavePath ())) 67 {68 json = sr. readToEnd (); 69 if (json! = "") 70 {71 config = JsonConvert. deserializeObject <T> (json); 72} 73 else74 {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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.