Quick Tip : Modifying INI files in C# and VB.Net

By | May 11, 2010

Currently I am doing a lot of start up scripts on a Citrix environment and a lot of it have to deal with Network device mapping, allocation of license keys for users and de-allocating them, provisioning Initialization files, etc.

I think I have a lot to share in terms of some very useful code snippets and this is one of it – modifying INI files. To give you a better idea on how it goes the image below with the item highlight is the portion of the ini we are modifying.

C# Code

public class IniFile
{
public string sPath;
public IniFile(string INIPath)
{
sPath = INIPath;
}
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string sSection,  string sKey, string sValue, string sFilePath);

[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string sSection,  string sKey, string sDefinition, StringBuilder sReturnValue, int iSize,  string sFilePath);

public void SetIniValue(string sSection, string sKey, string sValue)
{
 WritePrivateProfileString(sSection, sKey, sValue, this.sPath);
}

public string GetIniValue(string sSection, string sKey)
{
 StringBuilder sReturnValue = new StringBuilder(255);
 int i = GetPrivateProfileString(sSection, sKey, "", sReturnValue,  255, this.sPath);
 return sReturnValue.ToString();
}
}

Usage

IniFile myIniFile = new IniFile("C:\Sample.ini");
myIniFile.SetIniValue("Section1", "Key2", "Test Value");

And for those who want it in VB.net

Public Class IniFile
Public sPath As String

Public Sub New(ByVal INIPath As String)
 sPath = INIPath
End Sub

<DllImport("kernel32")> _
Private Shared Function WritePrivateProfileString(ByVal sSection As String, ByVal sKey As String, ByVal sValue As String, ByVal sFilePath As String) As Long
End Function

<DllImport("kernel32")> _
Private Shared Function GetPrivateProfileString(ByVal sSection As String, ByVal sKey As String, ByVal sDefinition As String, ByVal sReturnValue As StringBuilder, ByVal iSize As Integer, ByVal sFilePath As String) As Integer
End Function

Public Sub SetIniValue(ByVal sSection As String, ByVal sKey As String, ByVal sValue As String)
 WritePrivateProfileString(sSection, sKey, sValue, Me.sPath)
End Sub

Public Function GetIniValue(ByVal sSection As String, ByVal sKey As String) As String
 Dim sReturnValue As New StringBuilder(255)
 Dim i As Integer = GetPrivateProfileString(sSection, sKey, "", sReturnValue, 255, Me.sPath)
 Return sReturnValue.ToString()
End Function

End Class

Usage

Dim myIniFile As New IniFile("C:Sample.ini")
myIniFile.SetIniValue("Section1", "Key2", "Test Value")
Recommended

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.