using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; public class AIniLoader { private Dictionary<string, string> dIniNodes = new Dictionary<string, string>(); private Dictionary<string, string> dDefaultValues = new Dictionary<string, string>(); public void OnSetDefaultValue(string key, int value) { OnSetDefaultValue(key, value.ToString()); } public void OnSetDefaultValue(string key, string value) { if (dDefaultValues.ContainsKey(key)) { dDefaultValues[key] = value; } else { dDefaultValues.Add(key, value); } } private string fileName = ""; public void LoadIniFile(string sFileName) { fileName = sFileName; if (!File.Exists(sFileName)) { File.Create(sFileName).Close(); } else { StreamReader mysr = new StreamReader(sFileName, System.Text.Encoding.UTF8); string strline = ""; while ((strline = mysr.ReadLine()) != null) { string[] astr = strline.Split(new char[] { '=' }, 2); if (astr.Length != 2) { Console.WriteLine("Invalid line " + strline); continue; } dIniNodes.Add(astr[0], astr[1]); } mysr.Close(); } } public int OnGetIntValue(string sNodeName) { return typeParser.intParse(OnGetValue(sNodeName)); } public void OnSetValue(string sNodeName, string sValue) { if (dIniNodes.ContainsKey(sNodeName)) { dIniNodes[sNodeName] = sValue; } else { dIniNodes.Add(sNodeName, sValue); } } public string OnGetValue(string sNodeName) { if (!dIniNodes.ContainsKey(sNodeName)) { if (dDefaultValues.ContainsKey(sNodeName)) { return dDefaultValues[sNodeName]; } return ""; } return dIniNodes[sNodeName]; } public void OnSaveBack() { string shistory = ""; foreach (string str in dIniNodes.Keys) { shistory += str + "=" + dIniNodes[str] + "\n"; } foreach (string str in dDefaultValues.Keys) { if (dIniNodes.ContainsKey(str)) { continue; } shistory += str + "=" + dDefaultValues[str] + "\n"; } StreamWriter sw = new StreamWriter(fileName); sw.Write(shistory); sw.Close(); } } |
AIniLoader iniLoader = new AIniLoader(); iniLoader.LoadIniFile("Server.ini"); string ip = iniLoader.OnGetValue("serverIP"); int port = iniLoader.OnGetIntValue("serverPort"); |
serverIP=127.0.0.1 serverPort=999 |
欢迎光临 纳金网 (http://wwww.narkii.com/club/) | Powered by Discuz! X2.5 |