Sunday, December 11, 2005

Reading ini-file from C#




Here comes small utility class to read settings from old-fashioned-style .ini files
(general sketch only - it reparses file to read each setting):



using System;
using System.IO;
using System.Text.RegularExpressions;

namespace CommonUtilities
{
/// <summary>
/// Parse settings from ini-like files
/// </summary>
public class IniFile
{
static IniFile()
{
_iniKeyValuePatternRegex = new Regex(
@"((\s)*(?<Key>([^\=^\s^\n]+))[\s^\n]*
# key part (surrounding whitespace stripped)
\=
(\s)*(?<Value>([^\n^\s]+(\n){0,1})))
# value part (surrounding whitespace stripped)
"
,
RegexOptions.IgnorePatternWhitespace |
RegexOptions.Compiled |
RegexOptions.CultureInvariant );
}
static private Regex _iniKeyValuePatternRegex;

public IniFile(string iniFileName)
{
_iniFileName = iniFileName;
}

public string ParseFileReadValue(string key)
{
using( StreamReader reader =
new StreamReader(_iniFileName) )
{
do
{
string line = reader.ReadLine();
Match match =
_iniKeyValuePatternRegex.Match(line);
if( match.Success )
{
string currentKey =
match.Groups["Key"].Value as string;
if( currentKey != null &&
currentKey.Trim().CompareTo(key) == 0 )
{
string value =
match.Groups["Value"].Value as string;
return value;
}
}

}
while(reader.Peek() != -1);
}
return null;
}

public string IniFileName
{
get{ return _iniFileName; }
} private string _iniFileName;
}
}





[Listening to: Sax For Lovers - How Many Dreams]



5 comments:

Anonymous said...

Cool Thanks...

Unknown said...

Great! I tried and work "out of the box". Just so that others can test it quickly I added a Main function and a ini.txt file in c:\temp. This function can be placed just before public class IniFile:

public class test
{
static void Main(string[] args)
{
IniFile t = new IniFile(@"C:\temp\ini.txt");
String value;
value = t.ParseFileReadValue(@"URL");
Console.Write(value + "\n");
value = t.ParseFileReadValue(@"UserID");
Console.Write(value + "\n");
Console.Read()
}
}

Anonymous said...

Just note that it is caseSensitive

Anonymous said...

Also doesn't seem to take comments into account.

Anonymous said...

Thanks a lot.. Its worked for me