473,785 Members | 2,938 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading and parsing an INI file in C#

115 New Member
This class makes use of System.Collecti ons.Hashtable to enumerate all the settings in an INI file for easy access. Its very simplistic, and completely re-useable. Solid addition for any app that requires a settings file.

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4.  
  5. public class IniParser
  6. {
  7.     private Hashtable keyPairs = new Hashtable();
  8.     private String iniFilePath;
  9.  
  10.     private struct SectionPair
  11.     {
  12.         public String Section;
  13.         public String Key;
  14.     }
  15.  
  16.     /// <summary>
  17.     /// Opens the INI file at the given path and enumerates the values in the IniParser.
  18.     /// </summary>
  19.     /// <param name="iniPath">Full path to INI file.</param>
  20.     public IniParser(String iniPath)
  21.     {
  22.         TextReader iniFile = null;
  23.         String strLine = null;
  24.         String currentRoot = null;
  25.         String[] keyPair = null;
  26.  
  27.         iniFilePath = iniPath;
  28.  
  29.         if (File.Exists(iniPath))
  30.         {
  31.             try
  32.             {
  33.                 iniFile = new StreamReader(iniPath);
  34.  
  35.                 strLine = iniFile.ReadLine();
  36.  
  37.                 while (strLine != null)
  38.                 {
  39.                     strLine = strLine.Trim().ToUpper();
  40.  
  41.                     if (strLine != "")
  42.                     {
  43.                         if (strLine.StartsWith("[") && strLine.EndsWith("]"))
  44.                         {
  45.                             currentRoot = strLine.Substring(1, strLine.Length - 2);
  46.                         }
  47.                         else
  48.                         {
  49.                             keyPair = strLine.Split(new char[] { '=' }, 2);
  50.  
  51.                             SectionPair sectionPair;
  52.                             String value = null;
  53.  
  54.                             if (currentRoot == null)
  55.                                 currentRoot = "ROOT";
  56.  
  57.                             sectionPair.Section = currentRoot;
  58.                             sectionPair.Key = keyPair[0];
  59.  
  60.                             if (keyPair.Length > 1)
  61.                                 value = keyPair[1];
  62.  
  63.                             keyPairs.Add(sectionPair, value);
  64.                         }
  65.                     }
  66.  
  67.                     strLine = iniFile.ReadLine();
  68.                 }
  69.  
  70.             }
  71.             catch (Exception ex)
  72.             {
  73.                 throw ex;
  74.             }
  75.             finally
  76.             {
  77.                 if (iniFile != null)
  78.                     iniFile.Close();
  79.             }
  80.         }
  81.         else
  82.             throw new FileNotFoundException("Unable to locate " + iniPath);
  83.  
  84.     }
  85.  
  86.     /// <summary>
  87.     /// Returns the value for the given section, key pair.
  88.     /// </summary>
  89.     /// <param name="sectionName">Section name.</param>
  90.     /// <param name="settingName">Key name.</param>
  91.     public String GetSetting(String sectionName, String settingName)
  92.     {
  93.         SectionPair sectionPair;
  94.         sectionPair.Section = sectionName.ToUpper();
  95.         sectionPair.Key = settingName.ToUpper();
  96.  
  97.         return (String)keyPairs[sectionPair];
  98.     }
  99.  
  100.     /// <summary>
  101.     /// Enumerates all lines for given section.
  102.     /// </summary>
  103.     /// <param name="sectionName">Section to enum.</param>
  104.     public String[] EnumSection(String sectionName)
  105.     {
  106.         ArrayList tmpArray = new ArrayList();
  107.  
  108.         foreach (SectionPair pair in keyPairs.Keys)
  109.         {
  110.             if (pair.Section == sectionName.ToUpper())
  111.                 tmpArray.Add(pair.Key);
  112.         }
  113.  
  114.         return (String[])tmpArray.ToArray(typeof(String));
  115.     }
  116.  
  117.     /// <summary>
  118.     /// Adds or replaces a setting to the table to be saved.
  119.     /// </summary>
  120.     /// <param name="sectionName">Section to add under.</param>
  121.     /// <param name="settingName">Key name to add.</param>
  122.     /// <param name="settingValue">Value of key.</param>
  123.     public void AddSetting(String sectionName, String settingName, String settingValue)
  124.     {
  125.         SectionPair sectionPair;
  126.         sectionPair.Section = sectionName.ToUpper();
  127.         sectionPair.Key = settingName.ToUpper();
  128.  
  129.         if (keyPairs.ContainsKey(sectionPair))
  130.             keyPairs.Remove(sectionPair);
  131.  
  132.         keyPairs.Add(sectionPair, settingValue);
  133.     }
  134.  
  135.     /// <summary>
  136.     /// Adds or replaces a setting to the table to be saved with a null value.
  137.     /// </summary>
  138.     /// <param name="sectionName">Section to add under.</param>
  139.     /// <param name="settingName">Key name to add.</param>
  140.     public void AddSetting(String sectionName, String settingName)
  141.     {
  142.         AddSetting(sectionName, settingName, null);
  143.     }
  144.  
  145.     /// <summary>
  146.     /// Remove a setting.
  147.     /// </summary>
  148.     /// <param name="sectionName">Section to add under.</param>
  149.     /// <param name="settingName">Key name to add.</param>
  150.     public void DeleteSetting(String sectionName, String settingName)
  151.     {
  152.         SectionPair sectionPair;
  153.         sectionPair.Section = sectionName.ToUpper();
  154.         sectionPair.Key = settingName.ToUpper();
  155.  
  156.         if (keyPairs.ContainsKey(sectionPair))
  157.             keyPairs.Remove(sectionPair);
  158.     }
  159.  
  160.     /// <summary>
  161.     /// Save settings to new file.
  162.     /// </summary>
  163.     /// <param name="newFilePath">New file path.</param>
  164.     public void SaveSettings(String newFilePath)
  165.     {
  166.         ArrayList sections = new ArrayList();
  167.         String tmpValue = "";
  168.         String strToSave = "";
  169.  
  170.         foreach (SectionPair sectionPair in keyPairs.Keys)
  171.         {
  172.             if (!sections.Contains(sectionPair.Section))
  173.                 sections.Add(sectionPair.Section);
  174.         }
  175.  
  176.         foreach (String section in sections)
  177.         {
  178.             strToSave += ("[" + section + "]\r\n");
  179.  
  180.             foreach (SectionPair sectionPair in keyPairs.Keys)
  181.             {
  182.                 if (sectionPair.Section == section)
  183.                 {
  184.                     tmpValue = (String)keyPairs[sectionPair];
  185.  
  186.                     if (tmpValue != null)
  187.                         tmpValue = "=" + tmpValue;
  188.  
  189.                     strToSave += (sectionPair.Key + tmpValue + "\r\n");
  190.                 }
  191.             }
  192.  
  193.             strToSave += "\r\n";
  194.         }
  195.  
  196.         try
  197.         {
  198.             TextWriter tw = new StreamWriter(newFilePath);
  199.             tw.Write(strToSave);
  200.             tw.Close();
  201.         }
  202.         catch (Exception ex)
  203.         {
  204.             throw ex;
  205.         }
  206.     }
  207.  
  208.     /// <summary>
  209.     /// Save settings back to ini file.
  210.     /// </summary>
  211.     public void SaveSettings()
  212.     {
  213.         SaveSettings(iniFilePath);
  214.     }
  215. }
Example of usage:

INI File (C:\test.ini):

Expand|Select|Wrap|Line Numbers
  1. [AppSettings]
  2. msgPart1=Hello
  3. msgPart2= World
  4.  
  5. [Punctuation]
  6. ex=!
TestApp:

Expand|Select|Wrap|Line Numbers
  1. public class TestParser
  2. {
  3.     public static void Main()
  4.     {
  5.         IniParser parser = new IniParser(@"C:\test.ini");
  6.  
  7.         String newMessage;
  8.  
  9.         newMessage = parser.GetSetting("appsettings", "msgpart1");
  10.         newMessage += parser.GetSetting("appsettings", "msgpart2");
  11.         newMessage += parser.GetSetting("punctuation", "ex");
  12.  
  13.         //Returns "Hello World!"
  14.         Console.WriteLine(newMessage);
  15.         Console.ReadLine();
  16.     }
  17. }
May 28 '08 #1
5 92357
r035198x
13,262 MVP
What about comments in the ini file?
Jun 10 '08 #2
jamesjiao
1 New Member
If you look through the code - all you have to do is to add another conditional statement as shown here (modified sections in bold):
Expand|Select|Wrap|Line Numbers
  1. if (strLine.StartsWith("[") && strLine.EndsWith("]"))
  2. {
  3.   currentRoot = strLine.Substring(1, strLine.Length - 2);
  4. }
  5. else
  6. {
  7.   if (strLine.StartsWith("'")) {
  8.     // assuming comments start with the apostrophe
  9.     // do nothing
  10.   } else 
  11.   {
  12.     keyPair = strLine.Split(new char[] { '=' }, 2);
  13.     SectionPair sectionPair;
  14.     String value = null;
  15.  
  16.     if (currentRoot == null)
  17.       currentRoot = "ROOT";
  18.  
  19.     sectionPair.Section = currentRoot;
  20.     sectionPair.Key = keyPair[0];
  21.  
  22.     if (keyPair.Length > 1)
  23.       value = keyPair[1];
  24.  
  25.     keyPairs.Add(sectionPair, value);
  26.   }
  27. }
Jul 27 '09 #3
WernerCD
1 New Member
My kingdom for this parser in a class.cs file...

I'm trying to get this wedged into a class file so I can use it in a few places, since I really do like the layout of it, but when I move it and put it into a namespace it just acts all wonky on me.
Feb 11 '10 #4
invalidptr
1 New Member
FYI The whole thing will fail if you have a duplicate key pair. You may want to extend to handle that situation.
Dec 16 '14 #5
nick1908
1 New Member
Here is an open source library http://www.multipetros.gr/public-pro...s/confing-dll/ for ini files read/write. It's very well documented and uses indexers (like a dictionary) to contact with the properties. I suggest to give a try!
May 20 '15 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

20
33075
by: sahukar praveen | last post by:
Hello, I have a question. I try to print a ascii file in reverse order( bottom-top). Here is the logic. 1. Go to the botton of the file fseek(). move one character back to avoid the EOF. 2. From here read a character, print it, move the file pointer (FILE*) to 2 steps back (using fseek(fp, -2, SEEK_CUR)) to read the previous character. This seems to be ok if the file has a single line (i.e. no new line character). The above logic...
30
4588
by: siliconwafer | last post by:
Hi All, I want to know tht how can one Stop reading a file in C (e.g a Hex file)with no 'EOF'?
7
2339
by: M | last post by:
Hi, I need to parse text files to extract data records. The files will consist of a header, zero or more data records, and a trailer. I can discard the header and trailer but I must split the data records up and return them to an application. The complexity here is that I won't know the exact format of the files until run time. The files may or may not contain headers and trailers
21
6395
by: EdUarDo | last post by:
Hi all, I'm not a newbie with C, but I don't use it since more than 5 years... I'm trying to read a text file which has doubles in it: 1.0 1.1 1.2 1.3 1.4 2.0 2.1 2.2 2.3 2.4 I'm doing this (it's only a test trying to achieve the goal...):
2
3603
by: Jean-Marie Vaneskahian | last post by:
Reading - Parsing Records From An LDAP LDIF File In .Net? I am in need of a .Net class that will allow for the parsing of a LDAP LDIF file. An LDIF file is the standard format for representing LDAP objects. I need to be able to read the records from an LDIF file into ..Net. There exists a Perl module that will do exactly this called Net::LDAP::LDIF but I am wanting to port my code over to .Net and cannot find anything with similar...
11
3595
by: Freddy Coal | last post by:
Hi, I'm trying to read a binary file of 2411 Bytes, I would like load all the file in a String. I make this function for make that: '-------------------------- Public Shared Function Read_bin(ByVal ruta As String) Dim cadena As String = "" Dim dato As Array If File.Exists(ruta) = True Then
8
3228
by: Lonifasiko | last post by:
Hi, Using Process class I asynchronously launch an executable (black box executable) file from my Windows application. I mean asynchronously because I've got an EventHandler for "Exited" event. Therefore, when process finishes, "Exited" event is raised. This executable writes a long file for over 1-5 minutes, and I, from my application must read that file while is being generated.
7
4568
by: tackleberi | last post by:
hi, im having some trouble reading a file into java and then storing it in an array here the code i have so far: import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; import javax.swing.JOptionPane; public class samplecode {
2
2434
by: Srinivas3279 | last post by:
I am new to the C/C++ My Program: int main(int argc, _TCHAR* argv) { //Declarations FILE *fp;
2
1720
by: electromania | last post by:
Hi, Im reading a file, with 2 columns. this is working as Im reading I want to be able to count how many rows I've read and also add the all values as im reading from the second column, could some help plz This is the code #include <stdio.h> #include <stdlib.h>
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10330
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8976
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7500
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3654
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2880
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.