Tuesday, August 5, 2014

Reading Variables from .INI Files using C# and VB .NET

It is sometimes advised to store information in a separate file than to "hard code" them inside the program. This includes, for example, in SQL connections, the database name or the server name stored in a separate file, so you don't have to open the program project in Visual Studio just to change the configurations. This blog explains how to use an .INI file to store information there and retrieve that information inside your program.

1. Create an .INI file on notepad. Type the following on the file then save it as info.ini.


2. On your form, reference System.Runtime.InteropServices then add the following code:

In C#:





public static string strFilePath = Application.StartupPath + "\\info.ini";

[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileStringW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
     
private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, string lpReturnedString, int nSize, string lpFileName);
     
[DllImport("KERNEL32.DLL", EntryPoint = "WritePrivateProfileStringW")]
     
private static extern int WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFilename);


In VB .NET:


Dim strFilepath As String = My.Application.Info.DirectoryPath & "\info.ini"

Public Declare Unicode Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringW" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Int32, ByVal lpFileName As String) As Int32

3. Declare the following variables (global):

In C#:

In VB .NET:



4. Add the ReadIni() method:

In C#:

In VB .NET:


5. Show the contents to a message box.




No comments:

Post a Comment