Public class INIFILE
{
[Dllimport ("Kernel32")]
Private Static extern long writeprivateprofilestring (string section, string key, string Val, string filepath );
[Dllimport ("Kernel32")]
Private Static extern int getprivateprofilestring (string section, string key, string def, stringbuilder retval, int size, string filepath );
Public String getfilename
{
Get;
Set;
}
Public INIFILE (string filepath)
{
Getfilename = filepath;
}
/// <Summary>
/// Write the INI File
/// </Summary>
/// <Param name = "section"> </param>
/// <Param name = "key"> key </param>
/// <Param name = "value"> value </param>
Public void writevalue (string section, string key, string value)
{
Writeprivateprofilestring (section, key, value, getfilename );
}
/// <Summary>
/// Read the INI File
/// </Summary>
/// <Param name = "section"> </param>
/// <Param name = "key"> key of the data to be retrieved </param>
/// <Param name = "defvalue"> indicates that if the key does not exist or the data cannot be found, the value is returned. </param>
/// <Returns> </returns>
Public String readvalue (string section, string key, string defvalue)
{
Stringbuilder temp = new stringbuilder (255 );
Int I = getprivateprofilestring (section, key, defvalue, temp, 255, this. getfilename );
Return temp. tostring ();
}
}
Application:
Public partial class form1: Form
{< br> Public form1 ()
{< br> initializecomponent ();
}< br> INIFILE ini = new INIFILE ("C: \ config. ini ");
private void button#click (Object sender, eventargs e)
{< br> ini. writevalue ("Config", "Port", "COM1");
}
Private void button2_click (Object sender, eventargs E)
{
String Port = ini. readvalue ("Config", "Port", "com2 ");
}
}
Result:
Write:
[Config]
Port = COM1
Read:
COM1,
If I change it to string port = ini. readvalue ("Config", "port123", "com2");, the port value is com2 if the port123 key does not exist in the INI file.