C # how to read the INI File,

Source: Internet
Author: User

C # how to read the INI File,

The INI file is used in the recent project to read the INI file. The method is as follows:

 

Using System; using System. collections. generic; using System. linq; using System. text; using System. collections. specialized; using System. IO; using System. runtime. interopServices; using System. windows. forms; namespace test {// <summary> // IniFiles class /// </summary> public class IniFiles {public string FileName; // INI file name // string path = System. IO. path. combine (Application. startupPath, "pos. ini "); // declare to read and write INI files API function of the component [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, pass the INI file name public IniFiles (string AFileName) {// determine whether the file exists FileInfo fileInfo = new FileInfo (FileName); // Todo: Find out the usage of enumeration if ((! FileInfo. exists) {// | (FileAttributes. directory in fileInfo. attributes) // the file does not exist. Create the 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 Ide Nt, string Value) {if (! WritePrivateProfileString (Section, Ident, Value, FileName) {throw (new ApplicationException ("An error occurred while writing the INI file");} // read the INI file and specify 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, the Chinese string s = Encoding cannot be supported. 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 the 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. toSt Ring (Value);} // from the INI file, add all Ident in the specified Section name to the public void ReadSection (string Section, StringCollection Idents) in the list) {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, S TringCollection 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 functions from the INI file public void ReadSections (StringCollection SectionList) {// Note: it must be implemented using Bytes. 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 a specified Section to public void ReadSectionValues (string Section, NameValueCollection Values) in the list) {StringCollection KeyList = new StringCollection (); ReadSection (Section, KeyList); Values. clear (); foreach (string key in KeyList) {Values. add (key, ReadStri Ng (Section, key, "") ;}}/** // read all values of the specified Section to the list, // public void ReadSectionValues (string Section, NameValueCollection Values, char splitString) // {string sealuvalue; // string [] sectionValueSplit; // 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 ini file cannot be cleared "));}} // Delete the public void DeleteKey (string Section, string Ident) {WritePrivateProfileString (Section, Ident, null, FileName);} // Note: For Win9X, you need to implement the UpdateFile method to write the data in the buffer to the file // on Win NT, 2000, and XP, both are directly written to the file without buffering. Therefore, you do not need to implement UpdateFile // After modifying the INI file, you should call this method to update the buffer. Public void UpdateFile () {WritePrivateProfileString (null, FileName);} // check whether a key value in a Section has public bool ValueExists (string Section, string Ident) {StringCollection Idents = new StringCollection (); ReadSection (Section, Idents); return Idents. indexOf (Ident)>-1;} // ensure resource release ~ IniFiles () {UpdateFile ();}}}


Note: When using this class to read an INI file, the first line must be empty.

[Parm]
Xxxx = 16:42:04
IsOver =-1
EndTime = 11:30:08

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.