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

A Complete Win32 INI File Utility Class

Rate me:
Please Sign up or sign in to vote.
4.82/5 (61 votes)
28 May 2014CPOL3 min read 169K   8.6K   175   43
A complete wrapper for the Win32 INI APIs

Introduction

While it is no longer the suggested method for storing data by Microsoft, for legacy reasons many applications still need to read and write INI files. Win32 provides several methods for working with INI files, but these methods are not exposed by the .NET Framework. This article presents a simple class to allow a managed application to interact with INI files.

Background

An INI file is a specially formatted text file containing one or more sections. Each section can have one or more settings (or keys). An example file is shown below:

.
[section1]
key1=1
key2=string1
.
.
.

Using the Code

The attached IniFile.cs file contains all the code for the IniFile class. You create a new instance of this class by passing the path of the INI file to read and/or write to the constructor.

C#
//Create a new IniFile object.
IniFile iniFile = new IniFile(@"c:\boot.ini");

Reading from an INI File

Similar to the System.Data.DataReader.IDataReader interface, the IniFile class provides several methods for reading different types of data from an INI file. Each of these methods takes the form "GetX", where X is the requested data type of the return value. For example, to read a System.Int32 value from your INI file, you use the GetInt32 method.

C#
//Read an Int16 value from an INI file.
short value1 = iniFile.GetInt16("section1", "key1", 0);

//Read an Int32 value from an INI file.
int value2 = iniFile.GetInt32("section1", "key2", 0);

//Read a String from an INI file.
string value3 = iniFile.GetString("section1", "key3", "default value");

//Read an Double value from an INI file.
double value4 = iniFile.GetDouble("section1", "key4", 0.0);

//Read an Boolean value from an INI file.
bool value5 = iniFile.GetBoolean(quot;section1", "key5", true);

As shown above, each of these methods takes three parameters. The first specifies the name of the section to read from. The second specifies the specific key to read from. The final parameter specifies the value to return if the section/key is not found. Please note that string values are limited to 32KB or less. Attempting to read a setting that is more than 32KB in length will result in the data being truncated to 32KB.

The IniFile class also provides methods to enumerate the list of sections or keys in a file. Each of these methods returns an array of strings.

C#
//Get the list of sections in the INI file.
string [] sectionNames = iniFile.GetSectionNames();

//Get the list of keys in the first section.
string [] keyNames = iniFile.GetKeyNames(sectionNames[0]);

Finally, the IniFile class provides methods that allow a caller to read all of the keys in a given section at once. This functionality is provided by two functions: GetSectionValues and GetSectionValuesAsList.

GetSectionValues is the more convenient of the two. It returns all the key/value pairs in a section as a Dictionary<string, string> object. This makes it very easy to get the value of several properties at one time.

C#
//Get the key/value pairs in a section of the INI file as a Dictionary.

//Get the key/values in section1.
Dictionary<string, string> sectionValues = iniFile.GetSectionValues("section1");

string value1 = sectionValues["key1"];
string value2 = sectionValues["key2"];

If a section contains more than one value with the same key, GetSectionValues always returns the first one in the file. If you need to be able to get all the values in a section no matter what the key names are, you can use the GetSectionValuesAsList method.

C#
//Get the key/value pairs in a section of the INI file as a List.

//Get the key/values in section1.
List<KeyValuePair<string, string>> sectionValues;

sectionValues = iniFile.GetSectionValuesAsList("section1");

foreach (KeyValuePair<string, string> pair in sectionValues)
{
    //Process the keys here...
}

Both of these methods share the same 32KB limit as GetString. If your section can contain more than 32KB of data, read each setting separately.

Writing to an INI File

The IniFile class also provides methods to write to an INI file. The various overloads of the WriteValue method allow the caller to write strings, integers, or doubles to an INI file. Each of these functions takes three parameters. The first specifies the name of the section to write to. The second specifies the specific key to write to. The final parameter specifies the new value for the key. If the section and key already exist, the existing value is overwritten. If the specified section or key do not exist, they are automatically created.

C#
//Write a string to the iniFile
iniFile.WriteValue("section1", "key2", "Test value");

//Write a Int32 to the iniFile.
iniFile.WriteValue("section1", "key1", 128);

//Write a Double to the iniFile.
iniFile.WriteValue("section1", "key1", 42.8);

//Write a Boolean to the iniFile.
iniFile.WriteValue("section1", "key1", true);

Deleting Data from an INI File

The IniFile class provides methods to delete keys and sections from an INI file. Use DeleteKey to delete a specific key and DeleteSection to delete a complete section from an INI file.

C#
//Delete key2 from section1
iniFile.DeleteKey("section1", "key2");

//Delete section2 (including all keys)
iniFile.DeleteSection("section2");

History

  • 05/28/2014
    • Corrected return type of GetInt16
    • Added GetBoolean and new WriteValue method to write boolean values
    • GetDouble no longer throws an exception if the text value of the key could not be parsed. It now returns the default value in this case.
  • 11/18/2013
    • Fixed some spelling errors in comments. Added documentation about exceptions the constructor can throw.
  • 11/19/2007
    • Added parameter checking
    • Added DeleteKey and DeleteSection
    • Added notes about the 32KB limitation for most methods
  • 11/19/2007
    • Fixed XML comments
    • Added GetSectionValues and GetSectionValuesAsList
  • 8/14/2007 - Initial version

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)
United States United States
I've been a software engineer since 1999. I tend to focus on C# and .NET technologies when possible.

Comments and Discussions

 
PraiseThanks Pin
Member 1257815111-Jun-16 4:11
professionalMember 1257815111-Jun-16 4:11 
Questionbug taking section keys Pin
Jayson Ragasa17-Jun-15 2:02
Jayson Ragasa17-Jun-15 2:02 
AnswerRe: bug taking section keys Pin
wilsone817-Jun-15 8:23
wilsone817-Jun-15 8:23 
GeneralRe: bug taking section keys Pin
Jayson Ragasa19-Jun-15 0:45
Jayson Ragasa19-Jun-15 0:45 
QuestionUtf-8 Pin
Member 322723129-Mar-15 4:45
Member 322723129-Mar-15 4:45 
AnswerRe: Utf-8 Pin
wilsone84-Apr-15 8:28
wilsone84-Apr-15 8:28 
QuestionINI files on Unix machines Pin
Chad Knudson30-May-14 10:56
Chad Knudson30-May-14 10:56 
GeneralMy vote of 5 Pin
Volynsky Alex28-May-14 11:33
professionalVolynsky Alex28-May-14 11:33 
QuestionIs there a MFC/C++ version? Pin
Jason.LYJ27-May-14 15:29
professionalJason.LYJ27-May-14 15:29 
AnswerRe: Is there a MFC/C++ version? Pin
wilsone828-May-14 10:30
wilsone828-May-14 10:30 
Bugthe type of return value should be "short" Pin
Member 979673220-Nov-13 1:14
Member 979673220-Nov-13 1:14 
GeneralRe: the type of return value should be "short" Pin
wilsone828-May-14 10:57
wilsone828-May-14 10:57 
Questionbool/Boolean? Pin
The Mighty Atom19-Nov-13 4:40
The Mighty Atom19-Nov-13 4:40 
AnswerRe: bool/Boolean? Pin
wilsone828-May-14 10:58
wilsone828-May-14 10:58 
QuestionThank you very much... Pin
Osama Al Shammari12-Jul-13 23:38
professionalOsama Al Shammari12-Jul-13 23:38 
AnswerRe: Thank you very much... Pin
wilsone815-Jul-13 7:57
wilsone815-Jul-13 7:57 
GeneralRe: Thank you very much... Pin
Osama Al Shammari15-Jul-13 9:37
professionalOsama Al Shammari15-Jul-13 9:37 
Generalwin32 ini reader Pin
rams30178-Apr-13 21:22
rams30178-Apr-13 21:22 
GeneralMy vote of 5 Pin
Mokhammad Fathoni Rokhman29-Jan-13 21:53
Mokhammad Fathoni Rokhman29-Jan-13 21:53 
GeneralMy vote of 5 Pin
knestel23-May-11 2:28
knestel23-May-11 2:28 
GeneralMy vote of 5 Pin
JPFriederich12-May-11 1:53
JPFriederich12-May-11 1:53 
GeneralMy vote of 5 Pin
dania_ross22-Feb-11 19:34
dania_ross22-Feb-11 19:34 
GeneralGood Job Pin
lionxTR12-Dec-10 8:22
lionxTR12-Dec-10 8:22 
GeneralMy vote of 3 Pin
eleboys4-Sep-10 19:39
eleboys4-Sep-10 19:39 
QuestionHow to process GetSectionValuesAsList() Pin
alleyes4-Aug-09 10:39
professionalalleyes4-Aug-09 10:39 

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.