当前位置: 欣欣网 > 码农

C# 操作INI文件

2024-06-01码农

INI文件是一种简单的文本文件格式,通常用于存储配置信息。在Windows平台上,这种文件格式曾被广泛用于存储应用程序的配置数据。虽然XML和JSON等更现代的数据存储格式已经变得越来越流行,但在某些场景下,INI文件仍然是一个简单且实用的选择。

在C#中,虽然.NET Framework没有直接提供对INI文件的内置支持,但我们可以使用一些第三方库或者手动解析的方式来读写INI文件。本文将介绍如何使用C#手动解析和生成INI文件,并提供相应的示例代码。

INI文件格式

INI文件通常由多个节(p)组成,每个节下面可以包含多个键值对(Key-Value Pair)。以下是一个简单的INI文件示例:

[Database]
Server=localhost
Port=3306
Username=root
Password=secret
[Application]
WindowSize=800x600
Theme=Dark

手动解析INI文件

在C#中,我们可以使用 System.IO 命名空间中的类来读取和写入文件。以下是一个简单的示例,展示了如何手动解析上述INI文件:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
public classIniFileParser
{
private Dictionary<string, Dictionary<stringstring>> data = new Dictionary<string, Dictionary<stringstring>>();
publicvoidLoad(string filePath)
{
data.Clear();
string[] lines = File.ReadAllLines(filePath);
string currentp = null;
Dictionary<stringstring> currentpData = null;
foreach (string line in lines)
{
line = line.Trim();
if (line.StartsWith(";") || line.Length == 0// 忽略注释和空行
continue;
if (line.StartsWith("[") && line.EndsWith("]")) // 新节的开始
{
currentp = line.Substring(1, line.Length - 2).Trim();
currentpData = new Dictionary<stringstring>();
data[currentp] = currentpData;
}
elseif (currentp != null// 键值对
{
int separatorIndex = line.IndexOf('=');
if (separatorIndex > 0)
{
string key = line.Substring(0, separatorIndex).Trim();
stringvalue = line.Substring(separatorIndex + 1).Trim();
currentpData[key] = value;
}
}
}
}
publicstringGetValue(string p, string key)
{
if (data.ContainsKey(p) && data[p].ContainsKey(key))
return data[p][key];
returnnull// 或者可以抛出一个异常,表示找不到指定的键值对
}
}




使用示例:

var parser = new IniFileParser();
parser.Load("path/to/your/config.ini"); // 加载INI文件路径请根据实际情况修改
string server = parser.GetValue("Database""Server"); // 获取Database节下的Server键的值
Console.WriteLine($"Server: {server}"); // 输出获取到的值,例如:localhost

生成INI文件

生成INI文件的过程与解析相反,你需要将数据按照INI文件的格式写入到文本文件中。以下是一个简单的示例:

publicvoidSave(string filePath)
{
using (StreamWriter writer = new StreamWriter(filePath))
{
foreach (KeyValuePair<string, Dictionary<stringstring>> p in data)
{
writer.WriteLine($"[{p.Key}]");
foreach (KeyValuePair<stringstring> keyValue in p.Value)
{
writer.WriteLine($"{keyValue.Key}={keyValue.Value}");
}
writer.WriteLine(); // 空行分隔不同的节
}
}
}

IniFileParser 类中添加上述 Save 方法后,你可以通过以下方式调用它来生成INI文件:

var parser = new IniFileParser();
// ... 在此处填充parser的数据 ...
parser.Save("path/to/your/new_config.ini"); // 保存INI文件路径请根据实际情况修改

结论

虽然.NET没有内置对INI文件的支持,但通过手动解析和生成文本,我们仍然可以在C#中轻松地处理INI文件。上述示例代码提供了一个简单的INI文件解析器,它可以加载INI文件并允许你查询特定的键值对,同时还支持将数据保存回INI文件格式。这对于需要轻量级配置管理的应用程序来说是一个实用的工具。