c#读取ini文件

时间:2022-11-01 04:30:57


ini 文件(保存为test.ini):

[first]
one=one's Value
[second]
two=two's Value
[third]
key1=value1
key2=value2
key3=value3
key4=value4

说明,ini 由节点,关键字,和值组成。

C# 代码

ini 的读取

           string filePath = Path.GetFullPath(@"text.ini");
           IniFile inFile = new IniFile(filePath);

           //读取单个section的单个值
           string first = null;
           string second= null;
           first = inFile.ReadInivalue("first", "one");
           second= inFile.ReadInivalue("second", "two");
           //读取单个section的多个值
           string[] keys= new string[] { "key1", "key2", "key3", "key4"};
           ArrayList values = new ArrayList();
           for (int i = 0; i < 4; i++)
           {
               values.Add(inFile.ReadInivalue("third", keys[i]));
            }

ini 的写入


           string filePath = Path.GetFullPath(@"test.ini");
           IniFile iniFile = new IniFile(filePath);

           //在一个section中写入一个key
           iniFile.WriteInivalue("first", "one", "one's Value");
           iniFile.WriteInivalue("second", "two", "two's Value");

           //在一个section中写入多个key
           string[] keys = new string[] { "key1", "key2", "key3", "key4"};
           string[] values = new string[] { "value1", "value2", "value3","value4" };
           for (int i = 0; i < 4; i++)
           {
               iniFile.WriteInivalue("third", keys[i], values[i]);
           }