c#中ini文件读写的方法是什么
在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对应的值。
上一篇:android怎么实现跑马灯效果
下一篇:android中textview滚动到指定位置怎么实现
C#
webacc.exe是什么文件?webacc.exe是不是病毒
WINSYS.vbs是什么文件?WINSYS.vbs是不是病毒
winssh.exe是什么文件?winssh.exe是不是病毒
wt.exe是什么文件?wt.exe是不是病毒
winsysetm.exe是什么文件?winsysetm.exe是不是病毒
winstrve.exe是什么文件?winstrve.exe是不是病毒
winsysupd7.exe是什么文件?winsysupd7.exe是不是病毒
winsysupd.exe是什么文件?winsysupd.exe是不是病毒
winsysupd2.exe是什么文件?winsysupd2.exe是不是病毒
winsysupd8.exe是什么文件?winsysupd8.exe是不是病毒