Parsing INI in .Net : IniFile Class

June 1, 2012 at 12:43 AMNasif

Few days ago I needed INI file parser. One that lets me group standard ini file sections and add/update key-values. After googling quite a bit, the only solution that I found was called "IniFileParser"  from google code. I does work, but throws exception when you have an ini file that has valueless keys. It also seemed quite large (ini parsing should be very simple!)

So, sat down and wrote a simple class that can do the job. Parses ini file, allows easy access of sections and keys with indexer. Total of 200 or so lines (with comments), i.e very small footprint.

You can download the Source from here: IniFile.zip (2.63 kb)

Example of Supported INI File Format

;Supported commets are '#' and ';'
#this is also a comment

#following is example of sectionless key value
mykey=myvalue

[mysection]
anotherkey = anothervalue

[anothersection]
ValueLessKey
aKey                =  long            long               value

How to use:

var iniFile = new IniFile();
iniFile.LoadFile("myinifile.ini");
iniFile["mysection"]["anotherkey"] = "a new value";

//Add a new key and value in a new section
iniFile["myNewSection"]["myNewKey"] = "my new value";

//Add a valueless key
iniFile["mysection"]["ValueLessKey"] = null;

//To check if a key exists (useful for valueless key), use Dictionary.ContainsKey method
iniFile["mysection"].ContainsKey("mykey");

//To access/add sectionless key/values use string.Empty as the key
iniFile[string.Empty]["sectionlessKey"] = "a value";

//Retrieve INI content for saving as ini file
File.WriteAllText("myIniFile.ini", iniFile.Ini);

//If you have ini content already, you can pass the content without reloading the file
string iniContent = File.ReadAllText("myIniFile.ini");

//Now create the IniFile instance
var iniFile = new IniFile(iniContent);

Other Specifications:

  • Key and Value must be within the same line. Multi line values are not supported.
  • Removes empty more than 1 lines within a section; allows only 1 empty line per section. Only the first empty line within the section is kept.
  • Only '#' and ';' characters are treated as comments.
  • Allows only "key = value" syntax pattern.
  • Whitespaces in both key and value are disregarded.

IniFile.zip (2.63 kb)

Posted in:

Tags: , ,

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading