Click here to Skip to main content
6,635,160 members and growing! (16,571 online)
Email Password   helpLost your password?
Desktop Development » Files and Folders » Configuration Files     Intermediate License: The Code Project Open License (CPOL)

API-Less INI File Wrapper

By Tolgahan ALBAYRAK

Read, Write, Save INI files without using Windows APIs.
C# (C# 2.0, C# 3.0), .NET (.NET 2.0, .NET 3.0, .NET 3.5), Visual Studio (VS2005, VS2008), Dev
Posted:5 Nov 2008
Views:14,120
Bookmarked:38 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
17 votes for this article.
Popularity: 5.55 Rating: 4.51 out of 5

1

2
2 votes, 11.8%
3

4
15 votes, 88.2%
5

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:

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:

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:

//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:

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:

//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:

//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)

About the Author

Tolgahan ALBAYRAK


Member

Occupation: Software Developer (Senior)
Location: Turkey Turkey

Other popular Files and Folders articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 21 of 21 (Total in Forum: 21) (Refresh)FirstPrevNext
GeneralMinor changes to get it work PinmemberMember 466324423:13 1 Jun '09  
GeneralSection Name Casing Bug PinmemberPaul E. Bible8:39 1 Dec '08  
GeneralRe: Section Name Casing Bug PinmemberTolgahan ALBAYRAK11:56 1 Dec '08  
GeneralSuperb !!! Pinmemberashu fouzdar20:37 12 Nov '08  
GeneralVery Nice PinmemberPaul Conrad12:11 12 Nov '08  
GeneralRe: Very Nice PinmemberTolgahan ALBAYRAK23:44 12 Nov '08  
Generalcong.!! PinmemberMember 413265013:04 10 Nov '08  
GeneralRe: cong.!! PinmemberTolgahan ALBAYRAK13:21 10 Nov '08  
GeneralTerminal Services and Performance PinmemberMember 214447311:37 10 Nov '08  
GeneralRe: Terminal Services and Performance PinmemberTolgahan ALBAYRAK12:18 10 Nov '08  
GeneralPurpose? PinmemberDenis Vuyka9:43 10 Nov '08  
GeneralRe: Purpose? PinmemberTolgahan ALBAYRAK11:22 10 Nov '08  
GeneralRe: Purpose? PinmemberDenis Vuyka22:06 10 Nov '08  
GeneralRe: Purpose? PinmemberTolgahan ALBAYRAK22:56 10 Nov '08  
Generalregular expressions PinmemberE. del Ayre21:31 9 Nov '08  
GeneralRe: regular expressions PinmemberTolgahan ALBAYRAK10:31 10 Nov '08  
GeneralPerformance comparison -- benchmark app? Pinmemberbolivar1235:00 7 Nov '08  
GeneralRe: Performance comparison -- benchmark app? PinmemberTolgahan ALBAYRAK7:54 7 Nov '08  
GeneralRe: Performance comparison -- benchmark app? PinmvpJohn Simmons / outlaw programmer2:52 8 Nov '08  
GeneralRe: Performance comparison -- benchmark app? PinmemberTolgahan ALBAYRAK3:47 8 Nov '08  
GeneralRe: Performance comparison -- benchmark app? Pinmember Randor 9:22 14 Nov '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 5 Nov 2008
Editor: Chris Maunder
Copyright 2008 by Tolgahan ALBAYRAK
Everything else Copyright © CodeProject, 1999-2009
Web09 | Advertise on the Code Project