Last active
February 8, 2017 11:45
-
-
Save M4sterZer0/3020c1620ab0956b2879adbeeea795cc to your computer and use it in GitHub Desktop.
C# simple language system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Usage example: | |
Set language: language.initLanguage(0); //English | |
Get translation: language.getTranslation("menu.file"); | |
With multiple arguments: language.getTranslation("proversion", "Max Mustermann", "12/31/2017"); | |
Example .xml: | |
<language> | |
<!-- ENGLISH --> | |
<language langid="0" identifier="menu.file" text="File"/> | |
<language langid="0" identifier="proversion" text="Pro Version licensed for %s until %s"/> | |
<!-- GERMAN --> | |
<language langid="1" identifier="menu.file" text="Datei"/> | |
<language langid="1" identifier="proversion" text="Pro Version lizenziert für %s bis zum %s"/> | |
</language> | |
*/ | |
using System; | |
using System.Collections.Generic; | |
using System.Xml; | |
public static class language | |
{ | |
public class languageSentences | |
{ | |
public string identifier { get; set; } | |
public string text { get; set; } | |
} | |
public static List<languageSentences> lang = new List<languageSentences>(); | |
public static void initLanguage(int id) | |
{ | |
XmlReader xmlReader = XmlReader.Create(AppDomain.CurrentDomain.BaseDirectory + "\\data\\language.xml"); | |
while (xmlReader.Read()) | |
{ | |
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "language")) | |
{ | |
if (xmlReader.HasAttributes) | |
{ | |
if (int.Parse(xmlReader.GetAttribute("langid")) == id) | |
{ | |
lang.Add(new languageSentences | |
{ | |
identifier = xmlReader.GetAttribute("identifier"), | |
text = xmlReader.GetAttribute("text") | |
}); | |
} | |
} | |
} | |
} | |
} | |
public static string ReplaceFirst(string text, string search, string replace) | |
{ | |
int pos = text.IndexOf(search); | |
if (pos < 0) | |
{ | |
return text; | |
} | |
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length); | |
} | |
public static string getTranslation(string sentence, params object[] arguments) | |
{ | |
foreach (languageSentences tmp in lang) | |
{ | |
if (tmp.identifier == sentence) | |
{ | |
if (tmp.text.Contains("%s")) | |
{ | |
if (arguments == null) | |
{ | |
return "Error #1."; | |
} | |
if (tmp.identifier == sentence) | |
{ | |
string _tmp = tmp.text; | |
foreach (object o in arguments) | |
{ | |
_tmp = ReplaceFirst(_tmp, "%s", o.ToString()); | |
} | |
_tmp = _tmp.Replace("~n~", Environment.NewLine); | |
return _tmp; | |
} | |
} | |
else | |
{ | |
return tmp.text; | |
} | |
} | |
} | |
return "Error #2."; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment