C # Read ini

Source: Internet
Author: User

Although Microsoft has already suggested replacing the INI file with the Registry in windows, the INI file is still useful in practical applications, especially in the popularity of green software, more and more programs save some configuration information to the INI file.

An INI file is a text file consisting of several sections. under each heading with parentheses, there are several keywords and their corresponding values ):

  [Section]  Key=Value

VC provides API functions for reading and writing INI files, but the C # programming language launched by Microsoft does not have the corresponding method, next I will introduce a C # class for reading and writing INI files and use this class to save the coordinates of the form. When the program runs again, the form will be displayed at the last exit position.

INIFILE class:

using System;using System.IO;using System.Runtime.InteropServices;

Because we need to call API functions, we must createSystem. runtime. interopservicesNamespace to provide a set of classes that can be used to access COM objects in. NET and local APIs.

 

 

[C-sharp]View plaincopy 
  1. Using system. text;
  2. Namespace ini
  3. {
  4. Public class INIFILE
  5. {
  6. Public String path; // INI File Name
  7. [Dllimport ("Kernel32")]
  8. Private Static extern long writeprivateprofilestring (string section, string key,
  9. String Val, string filepath );
  10. [Dllimport ("Kernel32")]
  11. Private Static extern int getprivateprofilestring (string section, string key, string def,
  12. Stringbuilder retval, int size, string filepath );
  13. // Declare the API function for reading and writing INI files
  14. Public INIFILE (string inipath)
  15. {
  16. Path = inipath;
  17. }
  18. // Class constructor, passing the INI File Name
  19. Publicvoid iniwritevalue (string section, string key, string value)
  20. {
  21. Writeprivateprofilestring (section, key, value, this. Path );
  22. }
  23. // Write the INI File
  24. Publicstring inireadvalue (string section, string key)
  25. {
  26. Stringbuilder temp = new stringbuilder (255 );
  27. Int I = getprivateprofilestring (section, key, "", temp, 255, this. Path );
  28. Return temp. tostring ();
  29. }
  30. // Read the specified INI File
  31. }
  32. }
 

 

Call the INIFILE class:

Create a standard C # windows application project, and add three text boxes named sect, key, and Val to the form.

Add the following code:

Using ini; // create a namespace // Save the form coordinates when the form is closed
[C-sharp]View plaincopy
  1. Privatevoid form1_closing (Object sender, system. componentmodel. canceleventargs E)
  2. {
  3. INIFILE ini = new INIFILE ("C: // test. ini ");
  4. INI. iniwritevalue ("Loc", "X", this. Location. X. tostring ());
  5. INI. iniwritevalue ("Loc", "Y", this. Location. Y. tostring ());
  6. // The tostring method converts a number to a string.
  7. }
// When the form is started, read the value of the INI file and assign it to the form
[C-sharp]View plaincopy
  1. Privatevoid form1_load (Object sender, system. eventargs E)
  2. {
  3. INIFILE ini = new INIFILE ("C: // test. ini ");
  4. Point P = new point ();
  5. // Determine the return value to avoid null errors during the first Runtime
  6. If (INI. inireadvalue ("Loc", "x ")! = "") & (INI. inireadvalue ("Loc", "Y ")! = ""))
  7. {
  8. P. x = int. parse (INI. inireadvalue ("Loc", "x "));
  9. P. Y = int. parse (INI. inireadvalue ("Loc", "Y "));
  10. // Int. parse converts string to int
  11. This. Location = P;
  12. }
  13. }
  
==============================================
Other methods:
DllImport("kernel32.dll")]
public extern static int GetPrivateProfileString(string segName, string keyName, string sDefault, StringBuilder buffer, int nSize, string fileName);

Public extern static int getprivateprofilestringa (string segname, string keyname, string sdefault, byte [] buffer, int ilen, string filename); // ANSI version

[Dllimport ("kernel32.dll")]
Public extern static int getprivateprofilesection (string segname, stringbuilder buffer, int nsize, string filename );

[Dllimport ("kernel32.dll")]
Public extern static int writeprivateprofilesection (string segname, string svalue, string filename );

[Dllimport ("kernel32.dll")]
Public extern static int writeprivateprofilestring (string segname, string keyname, string svalue, string filename );

[Dllimport ("kernel32.dll")]
Public extern static int getprivateprofilesectionnamesa (byte [] buffer, int ilen, string filename );

 
[C-sharp]View plaincopy
  1. // Among the encapsulated methods, the most valuable one is to get all the sections S and all the keys. Most of the Code on the internet is incorrect. Here is a correct method:
  2. /// Return the set of all section names in the configuration file
  3. Public arraylist readsections ()
  4. {
  5. Byte [] buffer = new byte [65535];
  6. Int rel = 0; // getprivateprofilesectionnamesa (buffer, buffer. getupperbound (0), _ filename );
  7. Int icnt, IPOs;
  8. Arraylist = new arraylist ();
  9. String TMP;
  10. If (rel> 0)
  11. {
  12. Icnt = 0; IPOs = 0;
  13. For (icnt = 0; icnt <rel; icnt ++)
  14. {
  15. If (buffer [icnt] = 0x00)
  16. {
  17. TMP = system. Text. asciiencoding. Default. getstring (buffer, IPOs, icnt-IPOS). Trim ();
  18. IPOs = icnt + 1;
  19. If (TMP! = "")
  20. Arraylist. Add (TMP );
  21. }
  22. }
  23. }
  24. Return arraylist;
  25. }
  26. // Obtain all key values of a node
  27. Public arraylist readkeys (string sectionname)
  28. {
  29. Byte [] buffer = new byte [5120];
  30. Int rel = 0; // getprivateprofilestringa (sectionname, null, "", buffer, buffer. getupperbound (0), _ filename );
  31. Int icnt, IPOs;
  32. Arraylist = new arraylist ();
  33. String TMP;
  34. If (rel> 0)
  35. {
  36. Icnt = 0; IPOs = 0;
  37. For (icnt = 0; icnt <rel; icnt ++)
  38. {
  39. If (buffer [icnt] = 0x00)
  40. {
  41. TMP = system. Text. asciiencoding. Default. getstring (buffer, IPOs, icnt-IPOS). Trim ();
  42. IPOs = icnt + 1;
  43. If (TMP! = "")
  44. Arraylist. Add (TMP );
  45. }
  46. }
  47. }
  48. Return arraylist;
  49. }
 
 

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.