/* * 主要作用; * 从xml读取游戏配置信息或保存 */ using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Forms; using System.IO; using System.Xml; using System.Reflection; namespace Game { class Config { Keys up; Keys down; Keys left; Keys right; int time; public int Time { get { return time; } set { time = value; } } public Keys Up { get { return up; } set { up = value; } } public Keys Down { get { return down; } set { down = value; } } public Keys Left { get { return left; } set { left = value; } } public Keys Right { get { return right; } set { right = value; } } //读取游戏配置信息 public void GetXml() { XmlTextReader reader; if (File.Exists("Config.xml")) { reader = new XmlTextReader("Config.xml"); } else { Assembly asm = Assembly.GetExecutingAssembly(); Stream s = asm.GetManifestResourceStream("Game.Config.xml"); reader = new XmlTextReader(s); } try { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "up") { up = (Keys)Convert.ToInt32(reader.ReadElementString().Trim()); } else if (reader.Name == "down") { down = (Keys)Convert.ToInt32(reader.ReadElementString().Trim()); } else if (reader.Name == "left") { left = (Keys)Convert.ToInt32(reader.ReadElementString().Trim()); } else if (reader.Name == "right") { right = (Keys)Convert.ToInt32(reader.ReadElementString().Trim()); } else if (reader.Name == "time") { time = Convert.ToInt32(reader.ReadElementString().Trim()); } } } } catch { MessageBox.Show("读取游戏配置文件发生了错误 !","错误提示",MessageBoxButtons.OK,MessageBoxIcon.Error); } finally { if (reader != null) { reader.Close(); } } } //保存游戏配置信息 public void SetXml() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<config></config>"); XmlNode root = doc.SelectSingleNode("config"); XmlElement eleup = doc.CreateElement("up"); eleup.InnerText = Convert.ToInt32(up).ToString(); root.AppendChild(eleup); XmlElement eledown = doc.CreateElement("down"); eledown.InnerText = Convert.ToInt32(down).ToString(); root.AppendChild(eledown); XmlElement eleleft = doc.CreateElement("left"); eleleft.InnerText = Convert.ToInt32(left).ToString(); root.AppendChild(eleleft); XmlElement eleright = doc.CreateElement("right"); eleright.InnerText = Convert.ToInt32(right).ToString(); root.AppendChild(eleright); XmlElement eletime = doc.CreateElement("time"); eletime.InnerText = Convert.ToInt32(time).ToString(); root.AppendChild(eletime); doc.Save("Config.xml"); MessageBox.Show("恭喜,游戏配置保存成功!请重新启动游戏 !","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); } } } Config.xml文件 <config> <up>87</up> <down>83</down> <left>65</left> <right>68</right> <time>600</time></config>