private static void SaveConfig(Type type, string path, object ob) { PropertyInfo[] properties = type.GetProperties(); Dictionary <string, Dictionary <string, string> > contents = ConfigContents[type] = new Dictionary <string, Dictionary <string, string> >(); string lastSection = null; foreach (PropertyInfo property in properties) { ConfigSection config = property.GetCustomAttribute <ConfigSection>(); if (config != null) { lastSection = config.Section; } if (lastSection == null) { continue; } ConfigPropertyIgnore ignore = property.GetCustomAttribute <ConfigPropertyIgnore>(); if (ignore != null) { continue; } MethodInfo method = typeof(ConfigReader).GetMethod("Write", new[] { typeof(Type), typeof(string), typeof(string), property.PropertyType }); method.Invoke(ob, new[] { type, lastSection, property.Name, property.GetValue(ob) }); } List <string> lines = new List <string>(); foreach (KeyValuePair <string, Dictionary <string, string> > header in contents) { lines.Add($"[{header.Key}]"); foreach (KeyValuePair <string, string> entries in header.Value) { lines.Add($"{entries.Key}={entries.Value}"); } lines.Add(string.Empty); } if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } File.WriteAllLines(path, lines, Encoding.Unicode); }
private static void ReadConfig(Type type, string path, object ob) { if (!File.Exists(path)) { return; } PropertyInfo[] properties = type.GetProperties(); Dictionary <string, Dictionary <string, string> > contents = ConfigContents[type] = new Dictionary <string, Dictionary <string, string> >(); string[] lines = File.ReadAllLines(path); Dictionary <string, string> section = null; foreach (string line in lines) { Match match = HeaderRegex.Match(line); if (match.Success) { section = new Dictionary <string, string>(); contents[match.Groups["Header"].Value] = section; continue; } if (section == null) { continue; } match = EntryRegex.Match(line); if (!match.Success) { continue; } section[match.Groups["Key"].Value] = match.Groups["Value"].Value; } string lastSection = null; foreach (PropertyInfo property in properties) { ConfigSection config = property.GetCustomAttribute <ConfigSection>(); if (config != null) { lastSection = config.Section; } if (lastSection == null) { continue; } ConfigPropertyIgnore ignore = property.GetCustomAttribute <ConfigPropertyIgnore>(); if (ignore != null) { continue; } MethodInfo method = typeof(ConfigReader).GetMethod("Read", new[] { typeof(Type), typeof(string), typeof(string), property.PropertyType }); property.SetValue(ob, method.Invoke(null, new[] { type, lastSection, property.Name, property.GetValue(ob) })); } }