【问题标题】:C#: What is the easiest way to delete a Section and its Keys from an INIC#:从 INI 中删除 Section 及其键的最简单方法是什么
【发布时间】:2016-08-31 21:03:15
【问题描述】:

我有一个 INI 文件,它由多个部分和一个名为“路径”的键组成。 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();
}

【问题讨论】:

标签: c# .net winforms ini


【解决方案1】:

自己经历一下怎么样?这些方面的内容:

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);
}

缺乏异常和格式处理,但能胜任。

【讨论】:

  • 当然最好避免这样的文本处理,而您可以通过将 null 传递给 lpKeyName 参数来使用 WritePrivateProfileString 简单地删除整个部分。
【解决方案2】:

使用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
要与字符串关联的键的名称。如果 指定部分中不存在该键,已创建该键。如果 此参数为NULL,整个部分,包括所有条目 在该部分内,被删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 2012-09-30
    • 2012-07-11
    • 2017-12-25
    • 2010-09-05
    • 2011-04-02
    • 2023-03-17
    • 2016-12-03
    相关资源
    最近更新 更多