How to Write to INI Files in C#
- 1). Import the internal Windows classes. The first lines of code in the C# class must call the Windows kernel. The classes used to write to INI files are in the kernel32.dll file in the system directory. Import the file using the following code:
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string strSection, string strKeys,string myVal,string theFile);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string strSection, string strKeys, string myDef, StringBuilder theReturnedValue, int varSize, string theFile); - 2). Add a file path variable. The imported Windows classes need a path to the INI file. Set up a string variable that points to the path of the file. The code below creates a path variable with the location of the application's INI file.
string myFilePath = "C:\\myProgram\\myProgram.INI"; - 3). Create a function to write to the INI file. Using the kernel imported in step one, write to the INI file using the "WritePrivateProfileString" method. The code below creates a function to call the kernel's method.
public void WriteToMyINIFile(string theSection,string myKey,string myVal)
{
WritePrivateProfileString(theSection,myKey,myVal,this.myFilePath);
}
The "theSection" parameter is the section header in the INI file. Section headers are surrounded by brackets. The "myKey" is the key used in the file with the assigned "myVal" string. - 4). Read the newly added INI information. You need to read the INI value at some point in your code. The following code reads the key created in the previous step.
StringBuilder myString= new StringBuilder(100);
int iLoc = GetPrivateProfileString(mySection ,myKey,"",myString, 100, this.myFilePath);
Source...