public static T LoadTranslation <T>(string filepath) { if (File.Exists(filepath)) { Dictionary <string, string> Nodes = new Dictionary <string, string>(); var content = File.ReadAllLines(filepath); foreach (var line in content) { var node = line.Split('$'); if (node.Length == 2) { Nodes.Add(node[0], node[1]); } } int count = Nodes.Count; T translated = (T)(Activator.CreateInstance(typeof(T))); var properties = translated.GetType().GetProperties(); foreach (var property in properties) { if (property.PropertyType == typeof(string)) { var attr = property.GetCustomAttribute(typeof(NodeNameAttribute)); if (attr is NodeNameAttribute) { NodeNameAttribute a = (NodeNameAttribute)attr; if (Nodes.ContainsKey(a.NodeName)) { property.SetValue(translated, Nodes[a.NodeName]); count--; } } else { if (Nodes.ContainsKey(property.Name)) { property.SetValue(translated, Nodes[property.Name]); count--; } } } } if (count == 0) { return(translated); } } return(default(T)); }
public static bool WriteTranslation <T>(string filepath) { if (!File.Exists(filepath)) { using (var writer = new StreamWriter(filepath, true)) { T def = (T)(Activator.CreateInstance(typeof(T))); var properties = def.GetType().GetProperties(); foreach (var property in properties) { if (property.PropertyType == typeof(string)) { var attr = property.GetCustomAttribute(typeof(NodeNameAttribute)); if (attr is NodeNameAttribute) { NodeNameAttribute a = (NodeNameAttribute)attr; writer.Write(a.NodeName); } else { writer.Write(property.Name); } writer.Write('$'); var value = property.GetValue(def); if (value != null) { writer.WriteLine((string)value); } else { writer.Dispose(); if (File.Exists(filepath)) { File.Delete(filepath); } return(false); } } } writer.Flush(); return(true); } } return(false); }