config.xml写入和读取
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace ZhuoHuiSchoolRoom.ZhuoHuiClass
{
class Global
{
/// <summary>
/// 获取xml文件中的值
/// </summary>
/// <param name="xmlValues">键</param>
/// <returns></returns>
public static string getValues(string name)
{
XmlDocument xml = new XmlDocument();
//读取xml文件
xml.Load(System.Environment.CurrentDirectory + "\\config.xml");
foreach (XmlNode node in xml.ChildNodes)
{
if (node.Name == "SettingsFile")
{
foreach (XmlNode node1 in node.ChildNodes)
{
if (node1.Name == name)
{
foreach (XmlNode node2 in node1.ChildNodes)
{
if (node2.Name == "Value")
{
return node2.InnerText;
}
}
}
}
}
}
return "";
}
/// <summary>
/// 数据写入config.xml
/// </summary>
/// <param name="name">键</param>
/// <param name="values">值</param>
public static void setValues(string name, string values)
{
XmlDocument xml = new XmlDocument();
xml.Load(System.Environment.CurrentDirectory + "\\config.xml"); //获取xml文件路径
XmlNode XN = xml.SelectSingleNode("SettingsFile");
XN = XN.SelectSingleNode(name);
XN.SelectSingleNode("Value").InnerText = values;
xml.Save(System.Environment.CurrentDirectory + "\\config.xml");
}
public static string getIPValues()
{
XmlDocument doc = new XmlDocument();
doc.Load(System.Environment.CurrentDirectory + "\\ZhuoHuiSchoolroom.exe.config");
string IP = ((System.Xml.XmlNode)(doc)).InnerText;
return IP;
//XmlDocument xml = new XmlDocument();
////读取xml文件
//xml.Load(System.Environment.CurrentDirectory + "\\ZhuoHuiSchoolroom.exe.config");
//foreach (XmlNode node in xml.ChildNodes)
//{
// if (node.Name == "configuration")
// {
// foreach (XmlNode node1 in node.ChildNodes)
// {
// if (node1.Name == "applicationSettings")
// {
// foreach (XmlNode node2 in node1.ChildNodes)
// {
// if (node2.Name == "ZhuoHuiSchoolroom.Properties.Settings")
// {
// foreach (XmlNode node3 in node2.ChildNodes)
// {
// if (node3.Name == "setting")
// {
// foreach (XmlNode node4 in node3.ChildNodes)
// {
// if (node4.Name == "value")
// {
// return node3.InnerText;
// }
// }
// }
// }
// }
// }
// }
// }
// }
//}
}
}
}
config.xml文件内容示例
<?xml version="1.0" encoding="utf-8"?>
<SettingsFile>
<Width>
<Value>1024</Value>
</Width>
<Height>
<Value>768</Value>
</Height>
</SettingsFile>
写入
Global.setValues("Width", this.Width.ToString());
Global.setValues("Height", this.Height.ToString());
读取
string width = Global.getValues("Width");
string height = Global.getValues("Height");