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
      { 
      }
}

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM