C# 之三类文件的读写( .XML,.INI 和 .TXT 文件)
笔记之用,关于三类.xml, .ini, .txt 文件的 C# 读写,请多多指教!
1,第一类:.xml 文件的读写
先贴上xml文件,下面对这个文件进行操作:
<?xml version="1.0" encoding="utf-8"?> <NetWork name="GlobalNet" Version="2.0.0.0"> <Factory name="China" StationNum="0"> <Machine name="FireBird"> <IpAddr name="192.168.65.111" /> <ValidChannel num="1" /> <ValidChannel num="2" /> <ValidChannel num="3" /> </Machine> </Factory> <Factory name="UK" StationNum="1"> <Machine name="NuEagle"> <IpAddr name="192.168.65.180" /> </Machine> </Factory> <Factory name="USA" StationNum="2"> <Machine name="Felix"> <IpAddr name="192.168.65.48" /> </Machine> </Factory> </NetWork>
操作之前,有几点需要弄清:
a, 节点/元素:如下图Network,Factory,Machine这一类都可以称之为元素或节点;
b, 元素阶层(深度);最顶层为0,依次加1;如图NetWork的深度为0,Factory为1,Machine为2,IpAddr为3。
c, 属性; 属性的形式为:属性名=”属性值”,比如 name="GlobalNet" ,name就是属性,GlobalNet就是属性值。
C# 的xml的读取可用 XmlReader,这里说一下ReadToDescendant,它用来查找子代(子元素节点),并且可以定位到子节点,如图当找完工厂(Factory)后要去找机器(Machine):
using (XmlReader reader = XmlReader.Create(@"C:\Users\user\Desktop\network.xml")) { while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name.ToString()) { //依据工厂来划分每一个站 case "Factory": //获取工厂名以及工厂号 string factoryName = reader.GetAttribute("name"); string factoryNo = reader.GetAttribute("StationNum"); //获取工厂下的机器名 reader.ReadToDescendant("Machine"); string machineName = reader.GetAttribute("name"); //获取机器的IP reader.ReadToDescendant("IpAddr"); string machineIP = reader.GetAttribute("name"); break; } } } }
2,第二类:INI 文件的读写。
这里会用到kernel32这个库,他本身有两个我们可以拿来用的函数(WritePrivateProfileString,WritePrivateProfileString)去处理 .ini 文件;这里将读写放在一个类里,我们先来看看这个类的内容.
using System; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Ini { /// <summary> /// Create a New INI file to store or load data /// </summary> public class IniFile { public string path; [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section,string key,string val,string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath); /// <summary> /// INIFile 构造 /// </summary> /// <param name="INIPath"></param> public IniFile(string INIPath) { path = INIPath; } /// <summary> /// INI文件写入数据 /// </summary> /// <param name="Section"></param> /// Section name /// <param name="Key"></param> /// Key Name /// <param name="Value"></param> /// Value Name public void IniWriteValue(string Section,string Key,string Value) { WritePrivateProfileString(Section,Key,Value,this.path); } /// <summary> /// 从Ini文件读取数据值 /// </summary> /// <param name="Section"></param> /// <param name="Key"></param> /// <param name="Path"></param> /// <returns></returns> public string IniReadValue(string Section,string Key) { StringBuilder temp = new StringBuilder(255); int i = GetPrivateProfileString(Section,Key,"",temp,255,this.path); return temp.ToString(); } } }
那么对应MySQL的 my.ini 文件如何操作,下面将示范如何在mysqld区间读取并且改变server-id 这个键的值:
my.ini 节选:
[mysqld]
# The next three options are mutually exclusive to SERVER_PORT below.
# skip-networking
# shared-memory-base-name=MYSQL
# The Pipe the MySQL Server will use
# socket=MYSQL
# The TCP/IP Port the MySQL Server will listen on
port=3306
# Path to installation directory. All paths are usually resolved relative to this.
# basedir="C:/Program Files/MySQL/MySQL Server 5.7/"
……
# Binary Logging.
# log-bin
# Error Logging.
log-error="NENGKA.err"
# Server Id.
server-id=111
……
C#读写 my.ini :
//MySQL的配置文档的修改 IniFile ini = new IniFile("my.ini"); ini.IniReadValue("mysqld", "server-id"); string IPAdd = "123"; ini.IniWriteValue("mysqld", "server-id", IPAdd);
3, 第三类:C# 读写 Text。
如下,这段代码是读取mysql输出的内容(略有省略),为了简化输出,方便客户查看,所有需要做一个解析。
txt 文件内容:
Slave_IO_State: Waiting for master to send event
Master_Host: *.*.*.*
Connect_Retry: 60
Master_Log_File: mysql-bin.000001
Read_Master_Log_Pos: 10726644
Relay_Log_File: mysqld-relay-bin.000056
Relay_Log_Pos: 231871
Relay_Master_Log_File: mysql-bin.000001
……
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
……
Replicate_Do_DB: data1
Replicate_Wild_Ignore_Table:
Last_Errno: 0
Last_Error:
Skip_Counter: 0
Exec_Master_Log_Pos: 10726644
Relay_Log_Space: 232172
Until_Condition: None
Until_Log_File:
……
这里主要使用FileStream,StreamReader,不断的ReadLine找出关键字。
//简化MySQL命令的输出 bool Slave_IO_Running = false; bool Slave_SQL_Running = false; string file = @"C:\Users\user\Desktop\mysqloutput.txt"; using(FileStream fs = new FileStream(file,FileMode.Open,FileAccess.Read)) using (StreamReader sr = new StreamReader(fs)) { try { string currentLine = sr.ReadLine(); while (currentLine != null) { //判断Slave_IO_Running是否在运行 if (currentLine.Contains("Slave_IO_Running")) { Slave_IO_Running = currentLine.Split(':')[1].Trim() == "Yes" ? true : false; } //判断Slave_SQL_Running是否在运行 if (currentLine.Contains("Slave_SQL_Running")) { Slave_SQL_Running = currentLine.Split(':')[1].Trim() == "Yes" ? true : false; } currentLine = sr.ReadLine(); } fs.Close(); sr.Close(); } catch { } }