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

标签 c# .net winforms 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();
}

最佳答案

使用 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.

关于C#:从 INI 中删除部分及其键的最简单方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37061370/

相关文章:

c# - “DropDownList1”具有无效的 SelectedValue,因为它不存在于项目列表中。参数名称 : value

.net - 如何在 MVC4 的 APIController 中使用我自己的依赖解析器

c# - 绑定(bind) winforms datagridview rowheader

c# - 如果 null.Equals(null) 为什么我会得到 NullReferenceException

c# - 类型转换的性能

c# - 将多个参数发送到 ASP.NET MVC 中的操作

javascript - 使用 ASP.NET MVC JavaScript 的斐波那契算法

c# - 获取 Windows 窗体的大小

C#:如何确保在执行操作之前在 ListView 中选择了行或项目?

c# - Office.Interop.Word : How to add a picture to document without getting compressed