C # Read and Write INI files

Source: Internet
Author: User

INI format:

[Section1]

Keyword1 = value1

Keyword2 = value2

...

[Section2]

Keyword3 = value3

Keyword4 = value4

 

 

  1. Public ClassIniclass
  2. {
  3. Public String inipath;
  4. [Dllimport ("Kernel32")]
  5. Private Static extern long writeprivateprofilestring (
  6. String section, string key, string Val, string filepath );
  7. [Dllimport ("Kernel32")]
  8. Private Static extern int getprivateprofilestring (
  9. String section, string key,
  10. String def, stringbuilder retval,
  11. Int size, string filepath );
  12. /// <Summary>
  13. /// Constructor
  14. /// </Summary>
  15. /// <Param name = "inipath"> file path </param>
  16. Public iniclass (string inipath)
  17. {
  18. Inipath = inipath;
  19. }
  20. /// <Summary>
  21. /// Write the INI File
  22. /// </Summary>
  23. /// <Param name = "section"> Project Name (for example, [typename]) </param>
  24. /// <Param name = "key"> key </param>
  25. /// <Param name = "value"> value </param>
  26. Public void iniwritevalue (string section, string key, string value)
  27. {
  28. Writeprivateprofilestring (section, key, value, this. inipath );
  29. }
  30. /// <Summary>
  31. /// Read the INI File
  32. /// </Summary>
  33. /// <Param name = "section"> Project Name (for example, [typename]) </param>
  34. /// <Param name = "key"> key </param>
  35. Public String inireadvalue (string section, string key)
  36. {
  37. Stringbuilder temp = new stringbuilder (500 );
  38. Int I = getprivateprofilestring (section, key, "", temp, 500, this. inipath );
  39. Return temp. tostring ();
  40. }
  41. /// <Summary>
  42. /// Verify whether the file exists
  43. /// </Summary>
  44. /// <Returns> Boolean value </returns>
  45. Public bool existinifile ()
  46. {
  47. Return file. exists (inipath );
  48. }
  49. }

C # INI file read/write class

Using system;
Using system. IO;
Using system. runtime. interopservices;
Using system. text;
Using system. collections;
Using system. Collections. Specialized;

Namespace wuyisky {
/**/
/// <Summary>
/// Inifiles class
/// </Summary>
Public class inifiles
{
Public String filename; // INI File Name
// Declare the API function for reading and writing INI files
[Dllimport ("Kernel32")]
Private Static extern bool writeprivateprofilestring (string section, string key, string Val, string filepath );
[Dllimport ("Kernel32")]
Private Static extern int getprivateprofilestring (string section, string key, string def, byte [] retval, int size, string filepath );
// Class constructor, passing the INI File Name
Public inifiles (string afilename)
{
// Determine whether a file exists
Fileinfo = new fileinfo (afilename );
// Todo: Find out the usage of enumeration
If ((! Fileinfo. exists ))
{// | (Fileattributes. Directory in fileinfo. attributes ))
// The file does not exist. Create a file.
System. Io. streamwriter Sw = new system. Io. streamwriter (afilename, false, system. Text. encoding. Default );
Try
{
Sw. Write ("# Table configuration file ");
Sw. Close ();
}

Catch
{
Throw (New applicationexception ("INI file does not exist "));
}
}
// It must be a full path, not a relative path
Filename = fileinfo. fullname;
}
// Write the INI File
Public void writestring (string section, string Ident, string value)
{
If (! Writeprivateprofilestring (section, ident, value, filename ))
{
 
Throw (New applicationexception ("An error occurred while writing the INI file "));
}
}
// Read the specified INI File
Public String readstring (string section, string Ident, string default)
{
Byte [] buffer = new byte [65535];
Int buflen = getprivateprofilestring (section, ident, default, buffer, buffer. getupperbound (0), filename );
// The encoding method of 0 (the default code page of the system) must be set. Otherwise, Chinese characters cannot be supported.
String S = encoding. getencoding (0). getstring (buffer );
S = S. substring (0, buflen );
Return S. Trim ();
}

// Read integer
Public int readinteger (string section, string Ident, int default)
{
String intstr = readstring (section, ident, convert. tostring (default ));
Try
{
Return convert. toint32 (intstr );

}
Catch (exception ex)
{
Console. writeline (ex. Message );
Return default;
}
}

// Write an integer
Public void writeinteger (string section, string Ident, int value)
{
Writestring (section, ident, value. tostring ());
}

// Read Boolean
Public bool readbool (string section, string Ident, bool default)
{
Try
{
Return convert. toboolean (readstring (section, ident, convert. tostring (default )));
}
Catch (exception ex)
{
Console. writeline (ex. Message );
Return default;
}
}

// Write bool
Public void writebool (string section, string Ident, bool value)
{
Writestring (section, ident, convert. tostring (value ));
}

// From the INI file, add all ident in the specified section name to the list
Public void readsection (string section, stringcollection idents)
{
Byte [] buffer = new byte [16384];
// Idents. Clear ();

Int buflen = getprivateprofilestring (section, null, null, buffer, buffer. getupperbound (0 ),
Filename );
// Parse the Section
Getstringsfrombuffer (buffer, buflen, idents );
}

Private void getstringsfrombuffer (byte [] buffer, int buflen, stringcollection strings)
{
Strings. Clear ();
If (buflen! = 0)
{
Int start = 0;
For (INT I = 0; I <buflen; I ++)
{
If (buffer [I] = 0) & (I-Start)> 0 ))
{
String S = encoding. getencoding (0). getstring (buffer, start, I-Start );
Strings. Add (s );
Start = I + 1;
}
}
}
}
// Read the names of all the sections s from the INI File
Public void readsections (stringcollection sectionlist)
{
// Note: bytes must be used for implementation. stringbuilder can only obtain the first section.
Byte [] buffer = new byte [65535];
Int buflen = 0;
Buflen = getprivateprofilestring (null, buffer,
Buffer. getupperbound (0), filename );
Getstringsfrombuffer (buffer, buflen, sectionlist );
}
// Read all values of the specified section to the list
Public void readsectionvalues (string section, namevaluecollection values)
{
Stringcollection keylist = new stringcollection ();
Readsection (section, keylist );
Values. Clear ();
Foreach (string key in keylist)
{
Values. Add (Key, readstring (section, key ,""));
  
}
}
//// Read all values of the specified section to the list,
// Public void readsectionvalues (string section, namevaluecollection values, char splitstring)
// {String sectionvalue;
// String [] sectionvaluesp.pdf;
// Stringcollection keylist = new stringcollection ();
// Readsection (section, keylist );
// Values. Clear ();
// Foreach (string key in keylist)
//{
// Sectionvalue = readstring (section, key ,"");
// Sectionvaluesplit = sectionvalue. Split (splitstring );
// Values. Add (Key, sectionvaluesp.pdf [0]. tostring (), sectionvaluesp.pdf [1]. tostring ());
 
//}
//}
// Clear a Section
Public void erasesection (string section)
{
//
If (! Writeprivateprofilestring (section, null, null, filename ))
{

Throw (New applicationexception ("section in the INI file cannot be cleared "));
}
}
// Delete the key under a section
Public void deletekey (string section, string ident)
{
Writeprivateprofilestring (section, ident, null, filename );
}
// Note: For Win9x, You need to implement the updatefile method to write data in the buffer to the file.
// On Win NT, 2000, and XP, files are directly written without buffering. Therefore, you do not need to implement updatefile.
// After modifying the INI file, call this method to update the buffer zone.
Public void updatefile ()
{
Writeprivateprofilestring (null, filename );
}

// Check whether a key value in a section exists
Public bool valueexists (string section, string ident)
{
//
Stringcollection idents = new stringcollection ();
Readsection (section, idents );
Return idents. indexof (ident)>-1;
}

// Ensure resource release
~ Inifiles ()
{
Updatefile ();
}
}
}

C # Read and Write INI files

Related Article

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.