Advertisement
Guest User

Json settings

a guest
Aug 17th, 2015
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.23 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Web.Script.Serialization;
  4.  
  5. namespace MiscConsole
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             var settings = MySettings.Load();
  12.             settings.myInteger++;
  13.             settings.Save();
  14.         }
  15.  
  16.         class MySettings : AppSettings<MySettings>
  17.         {
  18.             public string myString = "Hello World";
  19.             public int myInteger = 1;
  20.         }
  21.     }
  22.  
  23.     public class AppSettings<T> where T : new()
  24.     {
  25.         private const string DEFAULT_FILENAME = "settings.json";
  26.  
  27.         public void Save(string fileName = DEFAULT_FILENAME)
  28.         {
  29.             File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(this));
  30.         }
  31.  
  32.         public static void Save(T pSettings, string fileName = DEFAULT_FILENAME)
  33.         {
  34.             File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(pSettings));
  35.         }
  36.  
  37.         public static T Load(string fileName = DEFAULT_FILENAME)
  38.         {
  39.             T t = new T();
  40.             if(File.Exists(fileName))
  41.                 t = (new JavaScriptSerializer()).Deserialize<T>(File.ReadAllText(fileName));
  42.             return t;
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement