K0D3R K0D3R - 10 months ago 72
Ini Question

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

I have an INI file that consists of multiple Sections, and a single key named "Path". Everything in the INI is loaded into a DataGridView on Load for manipulating the contents of the file.

INI Example:
[First Entry]
[Second Entry]
[Third Entry]

What would be the easiest possible method of deleting [Second Entry] that wouldn't wipe out the entire file?

Here's what I'm working with at the moment for Writing new info to the file:

INI Class:
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);


Using WritePrivateProfileString method you can delete the entire section by passing null value for lpKeyName to method this way:

[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");

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.