Read and Write INI files through window API kernel32.dll

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.