config.xml写入和读取
Posted _小马哥
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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");
以上是关于config.xml写入和读取的主要内容,如果未能解决你的问题,请参考以下文章