Click here to Skip to main content
15,867,330 members
Articles / Programming Languages / C#
Article

API-Less INI File Wrapper

Rate me:
Please Sign up or sign in to vote.
5.00/5 (24 votes)
5 Nov 2008CPOL 79.2K   1.4K   64   26
Read, Write, Save INI files without using Windows APIs.

Introduction

Using Windows APIs to read and write (WritePrivateProfileString, GetPrivateProfileString ) INI files is easy, but if you have to get or write data on your app many times, it could cause performance issues because the functions load the INI files on each call.

So, this class will help you managing ini data on memory.

Background

This class does not use the classical INI get or put methods. It loads an INI file on initialize, uses Regular Expressions to parse data, and uses a dictionary for managing section names and data.

Regular Expressions:

C#
static readonly Regex regRemoveEmptyLines =
    new Regex
    (
        @"(\s*;[\d\D]*?\r?\n)+|\r?\n(\s*\r?\n)*", 
        RegexOptions.Multiline | RegexOptions.Compiled
    );

static readonly Regex regParseIniData =
    new Regex
    (
        @"
        (?<IsSection>
            ^\s*\[(?<SectionName>[^\]]+)?\]\s*$
        )
        |
        (?<IsKeyValue>
            ^\s*(?<Key>[^(\s*\=\s*)]+)?\s*\=\s*(?<Value>[\d\D]*)$
        )",
        RegexOptions.Compiled | 
        RegexOptions.IgnoreCase | 
        RegexOptions.IgnorePatternWhitespace
    );

Dictionary type:

C#
Dictionary<string, NameValueCollection> data = 
    new Dictionary<string,NameValueCollection>();

Actually, I did not search much to see if there is something like this already. I needed it and I wrote it. And, I thought that someone might find this useful.

Using the code

Initializing:

C#
//Creates an empty ini document, you can add sections,
//keys and values dynamically. And you can save it anytime.
TA_INIDocument ini = new TA_INIDocument();

//Initializes an ini file, you can change its data and save
//it anytime
TA_INIDocument ini = new TA_INIDocument("C:\\sample.ini");

//Initializes an ini file with encoding. Sometimes ini files
//could have unicode data
TA_INIDocument ini = 
    new TA_INIDocument("C:\\sample.ini", Encoding.Unicode);

//Initializes ini data from stream
Stream iniStream;
TA_INIDocument ini = new TA_INIDocument(iniStream);

//Initializes ini data from stream with encoding
Stream iniStream;
TA_INIDocument ini =
    new TA_INIDocument(iniStream, Encoding.Unicode);

Getting and setting values:

C#
TA_INIDocument iniDoc;

//Getting key_value collection of defined section
NameValueCollection keysAndValues = iniDoc["sectionName"];
//Getting string value of defined key and section
string value = iniDoc["sectionName"]["keyName"];
string value = iniDoc["sectionName", "keyName"];
//Setting string value of defined key
iniDoc["sectionName"]["keyName"] = "newValue";
iniDoc["sectionName", "keyName"] = "newValue";
//Getting and Setting object value of defined key and section
object value = iniDoc["sectionName", "keyName", typeof(Int32)];
iniDoc["sectionName", "keyName", typeof(Rectangle)] =
    new Rectangle(0, 0, 200, 300);
//Getting and setting specific type values excepts string
//Primitive Types (included Decimal and DateTime)
//TA_INIDocument.Get{PrimitiveTypeName}(sectionName, keyName, [defaultValue])

bool bValue = 
    iniDoc.GetBoolean("sectionName", "keyName");

bool bValue = 
    iniDoc.GetBoolean("sectionName", "keyName", true);

iniDoc.SetValue("sectionName", "keyName", bValue);

DateTime dtValue = 
    iniDoc.GetDateTime("sectionName", "keyName");

DateTime dtValue = 
    iniDoc.GetDateTime("sectionName", "keyName", DateTime.MaxValue);

iniDoc.SetValue("sectionName", "keyName", dtValue);
//Other types (required that the type has TypeConverterAttribute)
//TA_INIDocument.GetValue<T>(sectionName, keyName, [T:defaultValue])

Rectangle rtValue =
    iniDoc.GetValue<Rectangle>("sectionName", "keyName");

Rectangle rtValue =
    iniDoc.GetValue<Rectangle>("sectionName", "keyName", Rectangle.Empty);

iniDoc.SetValue("sectionName", "keyName", rtValue);

Helper functions:

C#
//Helper Properties and Functions
TA_INIDocument iniDoc;
//Getting All Section Names
string[] sectionNames = iniDoc.SectionNames;
//Getting All Key Names of a Section
string[] keyNames = iniDoc.KeyNames("sectionName");
//Getting All Values of a Section
string[] allValues = iniDoc.SectionValues("sectionName");
//Check if section name exits
if (iniDoc.HasSection("sectionName"))
    Application.DoEvents();
//Check if key name exits of specified section
if (iniDoc.HasKey("sectionName", "keyName"))
    Application.DoEvents();

Saving all:

C#
//Saving all data
TA_INIDocument iniDoc;
Stream iniStream;

iniDoc.Save(iniStream);
//or
iniDoc.Save(iniStream, Encoding.Unicode);
//or
iniDoc.Save("C:\\sample.ini");
//or
iniDoc.Save("C:\\sample.ini", Encoding.Unicode);

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Turkey Turkey
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralTwo things not working Pin
Florin Pănescu13-Dec-18 2:33
Florin Pănescu13-Dec-18 2:33 
Questiongreat code !!! But.... Pin
ChristianGeiger13-Nov-13 2:03
ChristianGeiger13-Nov-13 2:03 
AnswerRe: great code !!! But.... Pin
Inlyrib3-Nov-15 2:27
Inlyrib3-Nov-15 2:27 
GeneralMy vote of 5 Pin
ChristianGeiger7-Nov-13 3:12
ChristianGeiger7-Nov-13 3:12 
BugCan not load a key that its value contain '=' Pin
Behzad Ebrahimi17-Apr-12 5:22
Behzad Ebrahimi17-Apr-12 5:22 
GeneralMinor changes to get it work Pin
Member 46632441-Jun-09 22:13
Member 46632441-Jun-09 22:13 
GeneralSection Name Casing Bug Pin
Paul E. Bible1-Dec-08 7:39
Paul E. Bible1-Dec-08 7:39 
GeneralRe: Section Name Casing Bug Pin
Tolgahan ALBAYRAK1-Dec-08 10:56
Tolgahan ALBAYRAK1-Dec-08 10:56 
GeneralSuperb !!! Pin
Ashutosh Phoujdar12-Nov-08 19:37
Ashutosh Phoujdar12-Nov-08 19:37 
GeneralVery Nice Pin
Paul Conrad12-Nov-08 11:11
professionalPaul Conrad12-Nov-08 11:11 
GeneralRe: Very Nice Pin
Tolgahan ALBAYRAK12-Nov-08 22:44
Tolgahan ALBAYRAK12-Nov-08 22:44 
Generalcong.!! Pin
Caraxe10-Nov-08 12:04
Caraxe10-Nov-08 12:04 
GeneralRe: cong.!! Pin
Tolgahan ALBAYRAK10-Nov-08 12:21
Tolgahan ALBAYRAK10-Nov-08 12:21 
GeneralTerminal Services and Performance Pin
Member 214447310-Nov-08 10:37
Member 214447310-Nov-08 10:37 
GeneralRe: Terminal Services and Performance Pin
Tolgahan ALBAYRAK10-Nov-08 11:18
Tolgahan ALBAYRAK10-Nov-08 11:18 
Actually, (i think) if .net framework works on t.s, and logged in account has file reading and writing permissions then, this code will probably work without any error or exception.

pls, fix me if i am wrong.

I havent been found the mean of life yet.

QuestionPurpose? Pin
Denis Vuyka10-Nov-08 8:43
Denis Vuyka10-Nov-08 8:43 
AnswerRe: Purpose? Pin
Tolgahan ALBAYRAK10-Nov-08 10:22
Tolgahan ALBAYRAK10-Nov-08 10:22 
GeneralRe: Purpose? Pin
Denis Vuyka10-Nov-08 21:06
Denis Vuyka10-Nov-08 21:06 
GeneralRe: Purpose? Pin
Tolgahan ALBAYRAK10-Nov-08 21:56
Tolgahan ALBAYRAK10-Nov-08 21:56 
Generalregular expressions Pin
E. del Ayre9-Nov-08 20:31
E. del Ayre9-Nov-08 20:31 
GeneralRe: regular expressions Pin
Tolgahan ALBAYRAK10-Nov-08 9:31
Tolgahan ALBAYRAK10-Nov-08 9:31 
QuestionPerformance comparison -- benchmark app? Pin
bolivar1237-Nov-08 4:00
bolivar1237-Nov-08 4:00 
AnswerRe: Performance comparison -- benchmark app? Pin
Tolgahan ALBAYRAK7-Nov-08 6:54
Tolgahan ALBAYRAK7-Nov-08 6:54 
GeneralRe: Performance comparison -- benchmark app? Pin
#realJSOP8-Nov-08 1:52
mve#realJSOP8-Nov-08 1:52 
GeneralRe: Performance comparison -- benchmark app? Pin
Tolgahan ALBAYRAK8-Nov-08 2:47
Tolgahan ALBAYRAK8-Nov-08 2:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.