CSharp .Net Tutorial: Reading and Writing INI

James Cloud
INI settings files are a popular and widely used type of data and settings storage. Though XML and other formats have become the main stream INI files are still an easy to use and simple solution to settings storage. INI files are easy to read and access through Visual CSharp .Net and Windows API, so if you are looking for a good way to store your settings use INI.

If you would like learn how to read and write from and to INI files in your Visual CSharp .Net project follow the guide bellow.

Reading and Writing INI Files

To write to your settings INI files you will first need to import the correct API functions, GetPrivateProfileString and WriteProfileString, for the Kernel32 system library. Place this code after your references above your namespace:

[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString")]
private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);

[DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString")]
private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);

With the proper API functions included you are able to create an INI reading method. Construct a public string void called GetINI with this source code:

public static string GetINI(string INISECTION, string INIKEY, string INIFILE)
{
int chrs = 256;
StringBuilder bffer = new StringBuilder(chrs);
string sDFLT = "";
if (GetPrivateProfileString(INISECTION, INIKEY, sDFLT, bffer, chrs, INIFILE) != 0)
{
return bffer.ToString();
}
else
{
return null;
}
}

Create another public void named WriteINI using the code provided below.

public void WriteINI(string INISECTION, string INIKEY, string NEWVALUE, string INIFILE)
{
WritePrivateProfileString(INISECTION, INIKEY, NEWVALUE, INIFILE);
}

Conclusion

Now that you have create both a reading and a writing INI function you can simply call either one to write or read desire your desired value. Here is an example of the writing function:

WriteINI("mySection", "myKey", "myValue", "C:\\myINI.ini");

This code will write the value "myValue" to the key "myKey" in the section "mySection" found in the INI file located at "C:\myINI.ini".

And the reading function:

String strTemp = "";

strTemp = GetINI("mySection", "myKey", "C:\\myINI.ini");

The above example will store the value of the key "myKey" found in the section "mySection" from the INI file located at "C:\myINI.ini" into strTemp.

Published by James Cloud

I like to program and do basically anything that has to do with technology and computers.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.