Barney

Settings Parsing

Jul 12th, 2013
622
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.26 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5.  
  6. /*
  7. Copyright C 2013 - Barney / chichi011
  8.  
  9. Do not remove this header !
  10. */
  11.  
  12. namespace PandaServer
  13. {
  14.     public static partial class Program
  15.     {
  16.         public static Dictionary<string, dynamic> Settings { get; set; }
  17.  
  18.         public static async Task<Dictionary<string, dynamic>> LoadSettingsAsync()
  19.         {
  20.             var temp = new Dictionary<string, dynamic>(25);
  21.             using (var reader = new StreamReader("server.ini"))
  22.             {
  23.                 string line = "";
  24.                 while ((line = await reader.ReadLineAsync()) != null)
  25.                 {
  26.                     if ((line = line.Trim()) == string.Empty || line.StartsWith("##") || line.StartsWith("'")) continue;
  27.                     var data = line.Split('=');
  28.                     if (data[1].StartsWith("^pair("))
  29.                         temp.Add(data[0], ParsePair(data[1]));
  30.                     else if (data[1].StartsWith("^tuple("))
  31.                         temp.Add(data[0], ParseTriple(data[1]));
  32.                     else
  33.                         temp.Add(data[0], ParseValue(data[1]));
  34.                 }
  35.             }
  36.  
  37.             return temp;
  38.         }
  39.  
  40.         public static dynamic ParseValue(string value)
  41.         {
  42.             dynamic item;
  43.             bool _bool;
  44.             int _int;
  45.             double _double;
  46.             if (!int.TryParse(value, out _int))
  47.                 if (!bool.TryParse(value, out _bool))
  48.                     if (!double.TryParse(value, out _double))
  49.                         item = value;
  50.                     else item = _double;
  51.                 else item = _bool;
  52.             else item = _int;
  53.             return item;
  54.         }
  55.  
  56.         static dynamic ParsePair(string expression)
  57.         {
  58.             var split = expression.Replace("^pair(", "").Replace(")", "").Split(',');
  59.             return Tuple.Create(ParseValue(split[0]), ParseValue(split[1]));
  60.         }
  61.  
  62.         static dynamic ParseTriple(string expression)
  63.         {
  64.             var split = expression.Replace("^tuple(", "").Replace(")", "").Split(',');
  65.             return Tuple.Create(ParseValue(split[0]), ParseValue(split[1]), ParseValue(split[2]));
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment