C#对ini文件的读写操作
在工厂里面,有很多年代比较久的测试设备在测试电子产品的时候,产生的测试文件有很大一部分都是ini的文件。这些ini文件都是比较传统的,现在大多数都是xml文件。这些ini文件在表达简单的数据的时候依然还是有它的用武之地。下面首先介绍一下ini文件(这种文件也可以用记事本打开)
ini 文件是Initialization File的缩写,即初始化文件,是windows的系统配置文件所采用的存储格式。】
格式:ini文件由节,键,值组成
节: [section]
参数:(键=值)name=value
注解使用分号表示(;)。在分号后面的文字,直到该行结尾都全部为注解。
; comment textINI文件的数据格式的例子(配置文件的内容) [Section1 Name]
一般形式如下:
[Section1]
KeyWord1 = Valuel
KeyWord2 = Value2
......
[Section2]
KeyWord3 = Value3
KeyWord4 = Value4
关键命名空间:System.Runtime.InteropServices
System.Runtime.InteropServices提供了相应的类或者方法来支持托管/非托管模块间的互相调用
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Runtime.InteropServices; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace IniFileOperator 9 {10 public class Program11 {12 static void Main(string[] args)13 {14 string str = @"C:\Users\wuxinlong\Desktop\demo\DemoTest\testFile";15 //创建一个ini文件,写入数据16 IniFile.IniWrite("data", "name", "wuxinlong", str + "\\Test.ini");17 IniFile.IniWrite("data", "sex", "man", str + "\\Test.ini");18 IniFile.IniWrite("Info", "address", "WuHanChina", str + "\\Test.ini");19 IniFile.IniWrite("Info", "height", "170", str + "\\Test.ini"); 20 21 //读取ini文件22 string str1 = IniFile.IniReadValue("data", "name", str + "\\Test.ini");23 Console.WriteLine(str1);24 string str2 = IniFile.IniReadValue("data", "sex", str + "\\Test.ini");25 Console.WriteLine(str2);26 string str3 = IniFile.IniReadValue("Info", "address", str + "\\Test.ini");27 Console.WriteLine(str3);28 string str4 = IniFile.IniReadValue("Info", "height", str + "\\Test.ini");29 Console.WriteLine(str4);30 Console.ReadKey();31 }32 }33 public class IniFile34 {35 [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]36 private static extern int GetPrivateProfileString(37 string section, string key, string def, StringBuilder retVal,38 int size, string filePath);39 //section:要读取的段落名40 //key: 要读取的键41 //defVal: 读取异常的情况下的缺省值42 //retVal: key所对应的值,如果该key不存在则返回空值43 //size: 值允许的大小44 //filePath: INI文件的完整路径和文件名45 46 [DllImport("kernel32")]47 private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);48 //section: 要写入的段落名49 //key: 要写入的键,如果该key存在则覆盖写入50 //val: key所对应的值51 //filePath: INI文件的完整路径和文件名52 53 54 //private static readonly string filePath = ConfigurationManager.AppSettings["filePath"];55 ///56 /// 读取ini文件57 /// 58 /// 59 /// 60 /// 61 ///返回键的值 62 public static string IniReadValue(string section, string key, string filePath)63 {64 StringBuilder temp = new StringBuilder(255);65 int i = GetPrivateProfileString(section, key, "", temp, 255, filePath);66 return temp.ToString();67 }68 69 ///70 /// 读取ini文件71 /// 72 /// 73 /// 74 /// 75 /// 76 public static void IniWrite(string section, string key, string value, string path)77 {78 WritePrivateProfileString(section, key, value, path);79 }80 }81 }