我有一个 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/