12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
编程知识 时间:2024-11-20 12:52:13
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
在C#中,可以使用System.IO命名空间下的StreamReader和StreamWriter类来读写INI文件。以下是一个简单的示例代码:using System;using System.IO;public class IniFile{private
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
在C#中,可以使用System.IO
命名空间下的StreamReader
和StreamWriter
类来读写INI文件。以下是一个简单的示例代码:
using System;using System.IO;public class IniFile{private string filePath;public IniFile(string filePath){this.filePath = filePath;}public string ReadValue(string section, string key){string value = "";using (StreamReader sr = new StreamReader(filePath)){string line;while ((line = sr.ReadLine()) != null){if (line.StartsWith($"[{section}]")){while ((line = sr.ReadLine()) != null){if (line.StartsWith(key)){value = line.Split('=')[1].Trim();break;}}break;}}}return value;}public void WriteValue(string section, string key, string value){bool sectionExists = false;string tempFile = Path.GetTempFileName();using (StreamReader sr = new StreamReader(filePath))using (StreamWriter sw = new StreamWriter(tempFile)){string line;while ((line = sr.ReadLine()) != null){if (line.StartsWith($"[{section}]")){sectionExists = true;}sw.WriteLine(line);}if (!sectionExists){sw.WriteLine($"[{section}]");}sw.WriteLine($"{key}={value}");}File.Delete(filePath);File.Move(tempFile, filePath);}}// 使用示例IniFile ini = new IniFile("example.ini");ini.WriteValue("Section1", "Key1", "Value1");string value = ini.ReadValue("Section1", "Key1");Console.WriteLine(value);
在以上示例中,IniFile
类封装了读取和写入INI文件的方法。通过ReadValue
方法可以读取指定section和key对应的值,通过WriteValue
方法可以写入指定section和key对应的值。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19