This class makes use of System.Collections.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. - using System;
-
using System.IO;
-
using System.Collections;
-
-
public class IniParser
-
{
-
private Hashtable keyPairs = new Hashtable();
-
private String iniFilePath;
-
-
private struct SectionPair
-
{
-
public String Section;
-
public String Key;
-
}
-
-
/// <summary>
-
/// Opens the INI file at the given path and enumerates the values in the IniParser.
-
/// </summary>
-
/// <param name="iniPath">Full path to INI file.</param>
-
public IniParser(String iniPath)
-
{
-
TextReader iniFile = null;
-
String strLine = null;
-
String currentRoot = null;
-
String[] keyPair = null;
-
-
iniFilePath = iniPath;
-
-
if (File.Exists(iniPath))
-
{
-
try
-
{
-
iniFile = new StreamReader(iniPath);
-
-
strLine = iniFile.ReadLine();
-
-
while (strLine != null)
-
{
-
strLine = strLine.Trim().ToUpper();
-
-
if (strLine != "")
-
{
-
if (strLine.StartsWith("[") && strLine.EndsWith("]"))
-
{
-
currentRoot = strLine.Substring(1, strLine.Length - 2);
-
}
-
else
-
{
-
keyPair = strLine.Split(new char[] { '=' }, 2);
-
-
SectionPair sectionPair;
-
String value = null;
-
-
if (currentRoot == null)
-
currentRoot = "ROOT";
-
-
sectionPair.Section = currentRoot;
-
sectionPair.Key = keyPair[0];
-
-
if (keyPair.Length > 1)
-
value = keyPair[1];
-
-
keyPairs.Add(sectionPair, value);
-
}
-
}
-
-
strLine = iniFile.ReadLine();
-
}
-
-
}
-
catch (Exception ex)
-
{
-
throw ex;
-
}
-
finally
-
{
-
if (iniFile != null)
-
iniFile.Close();
-
}
-
}
-
else
-
throw new FileNotFoundException("Unable to locate " + iniPath);
-
-
}
-
-
/// <summary>
-
/// Returns the value for the given section, key pair.
-
/// </summary>
-
/// <param name="sectionName">Section name.</param>
-
/// <param name="settingName">Key name.</param>
-
public String GetSetting(String sectionName, String settingName)
-
{
-
SectionPair sectionPair;
-
sectionPair.Section = sectionName.ToUpper();
-
sectionPair.Key = settingName.ToUpper();
-
-
return (String)keyPairs[sectionPair];
-
}
-
-
/// <summary>
-
/// Enumerates all lines for given section.
-
/// </summary>
-
/// <param name="sectionName">Section to enum.</param>
-
public String[] EnumSection(String sectionName)
-
{
-
ArrayList tmpArray = new ArrayList();
-
-
foreach (SectionPair pair in keyPairs.Keys)
-
{
-
if (pair.Section == sectionName.ToUpper())
-
tmpArray.Add(pair.Key);
-
}
-
-
return (String[])tmpArray.ToArray(typeof(String));
-
}
-
-
/// <summary>
-
/// Adds or replaces a setting to the table to be saved.
-
/// </summary>
-
/// <param name="sectionName">Section to add under.</param>
-
/// <param name="settingName">Key name to add.</param>
-
/// <param name="settingValue">Value of key.</param>
-
public void AddSetting(String sectionName, String settingName, String settingValue)
-
{
-
SectionPair sectionPair;
-
sectionPair.Section = sectionName.ToUpper();
-
sectionPair.Key = settingName.ToUpper();
-
-
if (keyPairs.ContainsKey(sectionPair))
-
keyPairs.Remove(sectionPair);
-
-
keyPairs.Add(sectionPair, settingValue);
-
}
-
-
/// <summary>
-
/// Adds or replaces a setting to the table to be saved with a null value.
-
/// </summary>
-
/// <param name="sectionName">Section to add under.</param>
-
/// <param name="settingName">Key name to add.</param>
-
public void AddSetting(String sectionName, String settingName)
-
{
-
AddSetting(sectionName, settingName, null);
-
}
-
-
/// <summary>
-
/// Remove a setting.
-
/// </summary>
-
/// <param name="sectionName">Section to add under.</param>
-
/// <param name="settingName">Key name to add.</param>
-
public void DeleteSetting(String sectionName, String settingName)
-
{
-
SectionPair sectionPair;
-
sectionPair.Section = sectionName.ToUpper();
-
sectionPair.Key = settingName.ToUpper();
-
-
if (keyPairs.ContainsKey(sectionPair))
-
keyPairs.Remove(sectionPair);
-
}
-
-
/// <summary>
-
/// Save settings to new file.
-
/// </summary>
-
/// <param name="newFilePath">New file path.</param>
-
public void SaveSettings(String newFilePath)
-
{
-
ArrayList sections = new ArrayList();
-
String tmpValue = "";
-
String strToSave = "";
-
-
foreach (SectionPair sectionPair in keyPairs.Keys)
-
{
-
if (!sections.Contains(sectionPair.Section))
-
sections.Add(sectionPair.Section);
-
}
-
-
foreach (String section in sections)
-
{
-
strToSave += ("[" + section + "]\r\n");
-
-
foreach (SectionPair sectionPair in keyPairs.Keys)
-
{
-
if (sectionPair.Section == section)
-
{
-
tmpValue = (String)keyPairs[sectionPair];
-
-
if (tmpValue != null)
-
tmpValue = "=" + tmpValue;
-
-
strToSave += (sectionPair.Key + tmpValue + "\r\n");
-
}
-
}
-
-
strToSave += "\r\n";
-
}
-
-
try
-
{
-
TextWriter tw = new StreamWriter(newFilePath);
-
tw.Write(strToSave);
-
tw.Close();
-
}
-
catch (Exception ex)
-
{
-
throw ex;
-
}
-
}
-
-
/// <summary>
-
/// Save settings back to ini file.
-
/// </summary>
-
public void SaveSettings()
-
{
-
SaveSettings(iniFilePath);
-
}
-
}
Example of usage:
INI File (C:\test.ini): - [AppSettings]
-
msgPart1=Hello
-
msgPart2= World
-
-
[Punctuation]
-
ex=!
TestApp: - public class TestParser
-
{
-
public static void Main()
-
{
-
IniParser parser = new IniParser(@"C:\test.ini");
-
-
String newMessage;
-
-
newMessage = parser.GetSetting("appsettings", "msgpart1");
-
newMessage += parser.GetSetting("appsettings", "msgpart2");
-
newMessage += parser.GetSetting("punctuation", "ex");
-
-
//Returns "Hello World!"
-
Console.WriteLine(newMessage);
-
Console.ReadLine();
-
}
-
}
5 91843
What about comments in the ini file?
If you look through the code - all you have to do is to add another conditional statement as shown here (modified sections in bold): -
if (strLine.StartsWith("[") && strLine.EndsWith("]"))
-
{
-
currentRoot = strLine.Substring(1, strLine.Length - 2);
-
}
-
else
-
{
-
if (strLine.StartsWith("'")) {
-
// assuming comments start with the apostrophe
-
// do nothing
-
} else
-
{
-
keyPair = strLine.Split(new char[] { '=' }, 2);
-
SectionPair sectionPair;
-
String value = null;
-
-
if (currentRoot == null)
-
currentRoot = "ROOT";
-
-
sectionPair.Section = currentRoot;
-
sectionPair.Key = keyPair[0];
-
-
if (keyPair.Length > 1)
-
value = keyPair[1];
-
-
keyPairs.Add(sectionPair, value);
-
}
-
}
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.
FYI The whole thing will fail if you have a duplicate key pair. You may want to extend to handle that situation.
Sign in to post your reply or Sign up for a free account.
Similar topics
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....
|
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'?
|
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...
|
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...
|
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...
|
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...
|
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....
|
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...
|
by: Srinivas3279 |
last post by:
I am new to the C/C++
My Program:
int main(int argc, _TCHAR* argv)
{
//Declarations
FILE *fp;
|
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...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
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,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
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,...
| |