In my Windows Forms application I have the need to write configuration to file. For this I am using the GetPrivateProfileString and WritePrivateProfileString methods. However, since I am using my own file types I decided to "extend" these functions to "enhance" the look and feel of my configuration files. Let's start with the WritePrivateProfileString method.

Code Snippet

public class DATWriter
{
[DllImport("KERNEL32.DLL")]
private static extern bool

WritePrivateProfileString(String section, String key, String value, String file);

public static int WriteValue(String section, String key, String value, String file)
{
section = section.Insert(0, "sect:");
key = key.Insert(0, "\t-> ");

WritePrivateProfileString(section, key, value, file);

return 0;
}
}


So, it works fine and dandy with one flaw. Each time it writes to the file, instead of overwriting a key and value if it already exists, it recreates the same key. So the file would look like this:

[sect:Human]
-> Name=David
-> Name=Dave

Instead of modifying the first key to have the value of 'Dave' it just creates a new key. So this is the first problem. Next is the GetPrivateProfileString method.

Code Snippet

public class DATReader
{
[DllImport("KERNEL32.DLL")]
private static extern bool GetPrivateProfileString(String section, String key, String errormsg, StringBuilder buffer, int Size, String file);

public static string ReadKey(String section, String key, String file)
{
String value = null;
StringBuilder buffer = new StringBuilder(256);

section = section.Insert(0, "sect:");
key = key.Insert(0, "\t-> ");

GetPrivateProfileString(section, key, "ERROR", buffer, 256, file);

value = buffer.ToString();
value = value.Remove(0, 1);
value = value.Remove(0, 3);

return value;
}
}


The problem with this is that it does not read the value and I don't really know how to fix this. Any help on this is appreciated.