These days when XML parsers, XML-based serialization and
Data Contract are readily available facilities, very much outdated INI files do not make much sense. The only reason I can possibly see would be the use of legacy INI data.
The functionality of INI files is so simple and the .NET BCL (
http://en.wikipedia.org/wiki/Base_Class_Library[
^]) is so powerful, that I see no problem in implementing of this functionality from scratch. I can see two convenient ways:
- Create a class to represent a compound dictionary key containing two strings, one representing section, another one — a key inside a section. For this class, you would need to define equality and hash function by overriding these two functions:
http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx[^],
http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx[^].
Let's call it SectionKey
class.
When this is done, the class can serve as a key type for the instantiation of the generic dictionary type System.Collections.Generic.Dictionary<SectionKey, string>
, where the second generic parameter introduced the INI values. Please see:
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx[^].
Read each INI file line by line; recognize either section name (use it as a "current section" during population procedure) or key-value pair, extract the key and pair. Compose the SectionKey
instance out of current section name and key, and the value to the dictionary, with this instance of the composite key.
That's is. Close the file and use the resulting dictionary for fast (O(1)) search of the value by section and key. If you want to compose the dictionary from some data, saving it to INI file is trivial; this is the foreach
loop by all key-value pairs.
- Same as previous, only with several dictionaries: top-level dictionary represents the sections only; its key is string representing an INI section, and its values are the dictionaries
Dictionary<string, string>
, each representing all key-value pairs (in the sense of INI format) of a given section.
—SA