C # Methods for reading INI files

Source: Internet
Author: User
Tags read ini file

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>
Class of Inifiles
</summary>
public class Inifiles
{
public string FileName; INI file name
String path = System.IO.Path.Combine (Application.startuppath, "Pos.ini");

API functions declaring read-write 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 INI file name
Public Inifiles (String afilename)
{
Determine if a file exists
FileInfo FileInfo = new FileInfo (afilename);
Todo: Figuring out the use of enumerations
if ((!fileinfo.exists))
{ //|| (Fileattributes.directory in Fileinfo.attributes))
File does not exist, build file
System.IO.StreamWriter SW = new System.IO.StreamWriter (Afilename, False, System.Text.Encoding.Default);
Try
{
Sw. Write ("#表格配置档案");
Sw. Close ();
}
Catch
{
Throw (New ApplicationException ("INI file does not exist"));
}
}
Must be a full path, not a relative path
FileName = Fileinfo.fullname;
}

Write INI file
public void WriteString (string section, String Ident, String Value)
{
if (! WritePrivateProfileString (section, Ident, Value, FileName))
{

Throw (New ApplicationException ("Error writing INI file"));
}
}

Read INI file specifies
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);
You must set the encoding for 0 (the system default code page), or you cannot support Chinese
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 integers
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 the 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);
Parsing a 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;
}
}
}
}

From the INI file, read all the names of the sections
public void Readsections (StringCollection sectionlist)
{
Note: It must be done with bytes, StringBuilder can only take the first section
byte[] Buffer = new byte[65535];
int buflen = 0;
Buflen = getprivateprofilestring (null, NULL, NULL, Buffer,
Buffer.getupperbound (0), FileName);
Getstringsfrombuffer (Buffer, Buflen, sectionlist);
}

Reads all the value of the specified section into 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, ""));
}
}

/**/
Reads all the value of the specified section into the list,
public void Readsectionvalues (string section, NameValueCollection Values,char splitstring)
{string Sectionvalue;
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, Sectionvaluesplit[0]. ToString (), sectionvaluesplit[1]. ToString ());
}
//}

Clear a section
public void Erasesection (string section)
{
if (! WritePrivateProfileString (section, NULL, NULL, FileName))
{
Throw (New ApplicationException ("Unable to clear section in INI file)");
}
}

Delete a key under a section
public void DeleteKey (string section, String Ident)
{
WritePrivateProfileString (section, Ident, NULL, FileName);
}

Note: For Win9x, it is necessary to implement the Updatefile method to write the data in the buffer to the file
In Win NT, 2000 and XP, are directly written files, no buffering, so, no need to implement Updatefile
After you finish modifying the INI file, you should call this method to update the buffer.
public void Updatefile ()
{
WritePrivateProfileString (NULL, NULL, NULL, FileName);
}

Checks if a key value exists under a section
public bool Valueexists (string section, String Ident)
{
StringCollection idents = new StringCollection ();
Readsection (section, idents);
Return Idents.indexof (Ident) >-1;
}

Ensure the release of resources
~inifiles ()
{
Updatefile ();
}
}
}

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

[Parm]
XXXX =2016-01-08 16:42:04
Isover =-1
EndTime =2016-01-11 11:30:08

C # Methods for reading INI files

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.