Due to the push for the adoption of XML configuration files, INI file handling was not built into the .NET Framework. However, INI files do still exist in legacy applications and can sometimes be found in newer software as well. So there needs to be a way to work with them from code. There are some available libraries, such as Nini and CommonLibrary.NET, which can perform this type of work, however, since this is part of the Quick-and-Dirty Series, here's a very simple example that will work for a lot of scenarios.
Interop Services to the rescue
Two kernel32.dll functions can be exposed to handle these INI files; WritePrivateProfileString and GetPrivateProfileString. The class IniFile listed below shows how to utilize these functions from Kernel32 via interop.
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace StoreLib.Configuration.Ini
{
public class IniFile
{
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string _section, string _key, string _val, string _filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string _section, string _key, string _def, StringBuilder _retVal, int _size, string _filePath);
public IniFile(string _path)
{
Path = _path;
}
//Write to INI File
public void WriteValue(string _section, string _key, string _value)
{
WritePrivateProfileString(_section, _key, _value, Path);
}
//Read from INI File
public string ReadValue(string _section, string _key)
{
StringBuilder sb = new StringBuilder(255);
int i = GetPrivateProfileString(_section, _key, "", sb, 255, Path);
return sb.ToString();
}
public string Path { get; set; }
}
}
Once the IniFile class is ready, reading a value is easy:
IniFile iniFile;
iniFile = newIniFile(@"C:\LegacyApplication\la.ini");
string dataSourceKey = "source1";
string dataSourceName = iniFile.ReadValue("DataSources", dataSourceKey);
Similarly, writing a value to the file is just as easy:
IniFile iniFile;
iniFile = newIniFile(@"C:\LegacyApplication\la.ini");
string appLoadKey= "splash";
string appLoadValue = "logo";
iniFile.WriteValue("AppLoad", appLoadKey, appLoadValue);
That's all there is to it. This is just one option for accessing an INI file and should be able to handle most instances of a section's simple key-value pair. Feel free to give it a try.
___________
Quick-and-Dirty Series - Hopefully still a sound solution, these may not be the best, fastest, or most appropriate methods of accomplishing a development task, however, they work and are fast to put in place.