C#读配置文件与读写XML文件
读取配置文件
配置文件一般是后缀格式为.config的文件,其实只要是保存了需要被代码识别的字符的文件都可称为配置文件,也就是什么txt啊,什么Json,excel表格都可以是配置文件,只要你保存了数据并要读到。在这里先介绍一下Vs自带的Config文件的API。
VS编辑器中,可在解决方案资源管理器内的下拉菜单中添加一个应用程序配置文件。如下图:
创建成功后会出现一个App.config文件点开进行编写。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="键" value ="值"/>
</appSettings>
</configuration>
这样成功存了一个键值对。
读取的代码如下:
using System;
using System.Configuration;//注意要引用命名空间
void Main()
{
//如果只能打出ConfigurationSettings.AppSettings,并提示弃用的话
//要在资源管理器中添加对System.Configuration的引用
//具体做法:右键资源管理器项目文件中的引用,选择添加,搜索System.Configuration,勾选上添加。
string result=ConfigurationManager.AppSettings["键"];
Console.WriteLine(result);//可得到“值”
}
读写Xml文件
xml是存储数据很常用的文件格式。
创建一个Xml文件:
using System.Xml.Linq;//执行xml的操作需要对此命名空间进行引用。
void CreatXmlText()
{
XDocument document=new XDocument();
XElement root =new XElement("根节点");
XElement root2=new XElement("子节点");
root2.SetAttributeValue("子节点属性","属性值");
root2.SetElementValue("子节点内容元素","内容");
root.Add(root2);
root.Save("d:\\XmlTestText.xml");//存储的文件路径
}
<?xml version="1.0" encoding="UTF-8"?>
-<根节点>
-<子节点 子节点属性="属性值">
<子节点内容元素>内容</子节点内容元素>
</子节点>
</根节点>
读取Xml
public static void ReadXml()
{
//存放xml文件的地址
string path ="d:\\XmlTestText.xml";
//读取路径下的文件
XDocument document =XDocument.Load(path);
//得到根节点内的内容
XElement root=document.Root;
//查找子节点内容
XElement childnode= root.Element("子节点");
//查找子节点属性
XAttribute attribute=childnode.Attribute("子节点属性");
Console.WriteLine(attribute.Value);
//查找具体内容
XElement result =childnode.Element("子节点内容元素");
Console.WriteLine(result.Value);
}
输出结果:
属性值
内容