C # writing and reading INI files

Source: Internet
Author: User

Code:

Using system. runtime. interopservices; public class iniclass {// path name of the INI file Public String inipath; // declare the write operation function writeprivateprofilestring () [dllimport ("Kernel32")] private Static extern long writeprivateprofilestring (string section, string key, string Val, string filepath); // declare the INI File Read operation function getprivateprofilestring () [dllimport ("Kernel32")] private Static extern int getprivateprofilestring (string section, string key, string def, stringbuilder retval, int size, string filepath); // string section: section name of the configuration file, for example, [magtask] // string key: section name of the configuration file is displayed in the INI file. For example, orderid = 8450 // string Def: if the INI file does not contain the field name or key name specified by the first two parameters, assign this value to the variable // stringbuilder retval: The cstring object that receives the value in the INI file, that is, the destination cache. for example, stringbuilder temp = new stringbuilder (500); // int size: the size of the destination cache. for example: 500 // string filepath: indicates the complete INI file name. // error-prone: for example. INI is placed in the same directory as the application. Enter "server. ini "The result cannot be read ==> resolved ". \ Server. ini "/// <summary> /// constructor // </Summary> /// <Param name =" inipath "> file path </param> Public iniclass (string inipath) {inipath = inipath ;} /// <summary> /// write the INI file /// </Summary> /// <Param name = "section"> Project Name (for example, [typename]) </param> /// <Param name = "key"> key </param> /// <Param name = "value"> value </param> Public void iniwritevalue (string section, string key, string value) {writeprivateprofilestring (section, key, value, this. inipath );} /// <summary> /// read the INI file /// </Summary> /// <Param name = "section"> Project Name (for example, [typename]) </param> // <Param name = "key"> key </param> Public String inireadvalue (string section, string key) {stringbuilder temp = new stringbuilder (500 ); int I = getprivateprofilestring (section, key, "", temp, 500, this. inipath); Return temp. tostring ();} /// <summary> /// check whether the file exists /// </Summary> /// <returns> Boolean value </returns> Public bool existinifile () {return file. exists (inipath );}}

 

Call code:

Public class taskorder: iniclass {Private Static readonly string key_tasksection = "magtask"; Private Static readonly string key_orderid = "orderid"; Private Static readonly string key_currentday = "currentday "; private Static readonly string key_day = "day"; Public taskorder (string path): Base (PATH) {}/// <summary> /// return the current task id /// </Summary> Public int taskmagid {get {return Int. parse (base. inireadvalue (key_tasksection, key_orderid);} set {base. iniwritevalue (key_tasksection, key_orderid, value. tostring () ;}/// <summary> /// returns the current time /// </Summary> Public datetime taskcurrentday {get {return datetime. parse (base. inireadvalue (key_currentday, key_day);} set {base. iniwritevalue (key_currentday, key_day, value. tostring ());}}}

 

INI file path:

private static TaskOrder objTask = new TaskOrder(AppDomain.CurrentDomain.BaseDirectory + "Config.ini");

 

The style of the INI file is as follows:

 

====================================== =

The following is an excerpt from others' blogs to deepen your understanding of the INI file:

 

An INI file is a text file with a specific structure. It consists of three parts:

[Section1]key 1 = value2key 1 = value2……[Section2]key 1 = value1key 2 = value2……

 

A file consists of several sections. Each section is divided into several keys and values ). The Win32 API functions getprivateprofilestring () and writeprivateprofilestring () in Windows implement read/write operations on inifiles respectively. They are located in kernel32.dll.

Unfortunately, the public class libraries under the. NET Framework used by C # do not provide classes for direct INI File Operations. Therefore, the only ideal method is to call API functions.

Then, the class libraries in the. NET Framework are based on managed code, while API functions are based on unmanaged code. (The Code executed under the control of the Runtime Library is called managed code. Instead, code running outside the Runtime Library is called unmanaged code .) How to implement operations between managed code and non-managed code ?. . NET Framework. runtime. the interopservices namespace provides a variety of members that support the com InterOP and platform call service. One of the most important attributes, dllimportattribute, can be used to define the platform call methods used to access unmanaged APIs, it provides the information necessary to call a function exported from an unmanaged DLL. The following describes how to implement the interoperability between C # and API functions.

Read operation:

[Dllimport ("Kernel32")] Private Static extern int getprivateprofilestring (string section, string key, string defval, stringbuilder retval, int size, string filepath); // section: the paragraph to be read // key: the Key to be read // defval: The value corresponding to the default value of // retval: key in case of an exception, if the key does not exist, null value // size: allowed size // filepath: the complete path and file name of the INI file are returned.

 

Write operation:

[Dllimport ("Kernel32")] Private Static extern long writeprivateprofilestring (string section, string key, string Val, string filepath); // section: name of the paragraph to be written // key: the key to be written. If the key exists, it overwrites the complete path and file name of the file written to // VAL: Key. // filepath: ini
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.