C#:从 INI 中删除部分及其键的最简单方法是什么

C#: What is the easiest way to delete a Section and its Keys from an INI

我有一个包含多个部分的 INI 文件和一个名为 "Path" 的键。 INI 中的所有内容都在加载时加载到 DataGridView 中,用于操作文件的内容。

INI Example:
[First Entry]
Path=C:\test1.txt
[Second Entry]
Path=C:\test2.txt
[Third Entry]
Path=C:\test3.text

删除 [Second Entry] 且不会清除整个文件的最简单方法是什么?

这是我目前正在使用的将新信息写入文件的方法:

INI Class:
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string fileName);

public void Write(string section, string key, string value)
{
WritePrivateProfileString(section, key, value.ToLower(), path);
}

Form Button:
private void WriteINI()
{
myINI.Write(txtName.Text, "Path", txtPath.Text);
ReadINI();
}

你自己经历一下如何?这些线上的东西:

private static void RemoveSectionFromIniFile(string file, string section)
{
    using (var reader = File.OpenText(file))
    {
        using (var writer = File.CreateText(file + ".tmp"))
        {
            var i = false;
            while (reader.Peek() != -1)
            {
                var line = reader.ReadLine();
                if (!string.IsNullOrWhiteSpace(line))
                {
                    if (line.StartsWith("[") && line.EndsWith("]"))
                    {
                        if (i) i = false;
                        else if (line.Substring(1, line.Length - 2).Trim() == section) i = true;
                    }
                }
                if (!i) writer.WriteLine(line);
            }
        }
    }
    File.Delete(file);
    File.Move(file + ".tmp", file);
}

缺少异常和格式处理,但可以完成工作。

使用 WritePrivateProfileString 方法,您可以通过将 lpKeyName 的空值传递给方法来删除整个部分:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool WritePrivateProfileString(
       string lpAppName, string lpKeyName, string lpString,string lpFileName);

private void button1_Click(object sender, EventArgs e)
{
    WritePrivateProfileString("Second Entry", null, null, @"d:\test.ini");
}

lpKeyName
The name of the key to be associated with a string. If the key does not exist in the specified section, it is created. If this parameter is NULL, the entire section, including all entries within the section, is deleted.