要从C#中的INI文件中读取值,可以使用以下方法:
以下是一个使用手动解析INI文件的示例代码:
using System;
using System.IO;
using System.Collections.Generic;
public class IniFile
{
private Dictionary<string, Dictionary<string, string>> sections = new Dictionary<string, Dictionary<string, string>>();
public IniFile(string filePath)
{
var lines = File.ReadAllLines(filePath);
Dictionary<string, string> currentSection = null;
foreach (var line in lines)
{
if (line.StartsWith("[") && line.EndsWith("]"))
{
var sectionName = line.Substring(1, line.Length - 2);
currentSection = new Dictionary<string, string>();
sections[sectionName] = currentSection;
}
else if (currentSection != null && line.Contains("="))
{
var parts = line.Split('=');
var key = parts[0].Trim();
var value = parts[1].Trim();
currentSection[key] = value;
}
}
}
public string GetValue(string section, string key)
{
if (sections.TryGetValue(section, out var sectionData) && sectionData.TryGetValue(key, out var value))
{
return value;
}
return null;
}
}
使用此类,可以从INI文件中读取值,例如:
var iniFile = new IniFile("example.ini");
var value = iniFile.GetValue("SectionName", "KeyName");
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云