Read/Write settings to INI File using C#

21. October 2009 18:12

C# Code Snippets 

When we design application we always face problems to save settings for the application and to achieve that we use different options available to us. A very common method to use in accordance of complexity XML files, Registry, Application.config or other/normal files. Best option is to use application configuration file but it seems that most of the people are not fully aware with the usage of the application configuration file. I will discuss late on the application configuration file a.k.a. app.config, but here is the way to use the INI files to save application settings.
Here I am using a simple class which has two methods Write & Read methods which internally calls the functions inside the Kernel32.dll which are WritePrivateProfileString and ReadPrivateProfileString. Both methods take parameters and write it to the INI file. Here is the complete listing of the class which can be use to read and write settings to the INI file.
INI files have sections and keys from where the data can be read on the combination of the sections and keys. As there can be a common key in different sections of the INI file. A section is defined in [SECTION NAME] and then it have a Key and its KeyValue.

class INIFile
        private string filePath;
        private static extern long WritePrivateProfileString(string section,
        string key,
        string val,
        string filePath);

        private static extern int GetPrivateProfileString(string section,
        string key,
        string def,
        StringBuilder retVal,
        int size,
        string filePath);
        public INIFile(string filePath)
            this.filePath = filePath;

        public void Write(string section, string key, string value)
            WritePrivateProfileString(section, key, value.ToLower(), this.filePath);

        public string Read(string section, string key)
            StringBuilder SB = new StringBuilder(255);
            int i = GetPrivateProfileString(section, key, "", SB, 255, this.filePath);
            return SB.ToString();
        public string FilePath
            get { return this.filePath; }
            set { this.filePath = value; }

Now when you have to perform the read and write operations to the INI file you have to just call the Write and Read method from the above class. Initialize the above class anywhere in your application and then call the below methods to work.

To write a new entry to an INI file use the write method. As you can see in the below method you need to first initialize a class which takes in the path of the INI fie. The write method takes 3 arguments which have Section, Key and KeyValue respectively. I have used a single section and a key to demonstrate the usage, but you can call the write method a number of time to write different settings value.

INIFile inif = new INIFile("D:\\config.ini");
inif.Write("Database", "Devs", "sa");

When the write is complete to the INI file, open the file to see the newly written values. Your file should look like the one below.

To read the particular value from the INI file use the read method. It takes in 2 arguments i.e. Section and Key respectively to read a KeyValue.

INIFile inif = new INIFile("D:\\config.ini");
Console.WriteLine("The Value is:" +inif.Read("Database", "Devs"));

I have just displayed the value after reading from the file after the write operation is completed. You can set a local variable to preserve the value and then take a required action.


Currently rated 4.9 by 14 people

C# Method: Encrypting a string using MD5 algorithm

20. July 2009 00:40

C# Code Snippets 

Encrypting a string using the MD5 algorithm

This C# method will encrypt any string using MD5 algorithm. It generates the same hash as the PHP MD5() function

using System;using System.Collections.Generic;
using System.Linq;using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
namespace EncryptString
    class Program
        public static string EncodePassword(string originalPassword)
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;
            md5 = new MD5CryptoServiceProvider();
            originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
            encodedBytes = md5.ComputeHash(originalBytes);
            return Regex.Replace(BitConverter.ToString(encodedBytes), "-", "").ToLower();
         static void Main(string[] args)
            Console.WriteLine("Enter a string to Encrypt");
            string strEnc = Console.ReadLine();
Currently rated 3.0 by 2 people

GUIDs in C# / SQL

26. June 2009 15:37

C# SQL Server Code Snippets 

GUID pronounced as goo'id - Globally unique identifier is a 128-bit integer that can be used to uniquely identify something. If you want to identify the large collection of data GUID is the best approach in my view. Also you can use the autoincremental integer to identify records, this is the basic approach programmer's use.

GUID method can be found under the System namespace and it also provides some overloads. Here is how we can use the GUID overloads:

System.Guid.NewGuid().ToString();    //c93ded50-7cce-4f3a-b8aa-5a1a34d80b14
System.Guid.NewGuid().ToString("N"); //636bdfd2bbc541229fbc6b869995ce6f
System.Guid.NewGuid().ToString("D"); //45e602b6-0904-47ac-a764-a5522f56f40f
System.Guid.NewGuid().ToString("B"); //{68f55508-f72c-4a38-b96b-f493c3c5adb9}
System.Guid.NewGuid().ToString("P"); //(1c2e52a7-e384-445e-b80a-e8704c6ecbd6)

To create GUID in SQL Server use the simple select statement:


 No Rating

Set the default printer for printing programatically

16. June 2009 15:17

C# Code Snippets 

You need to print the document but you don't want to go to control panel or printer and faxes options and just want to get it changed automatically. You can even set the shared local network printer with this code.

Just with the code you can override the system settings and change the default printer for your system.

You need to use the namespace so in order to use the DLLImport attribute.

using System.Runtime.Interopservices;
//Set default printer to the one available with your system or network.
private static extern bool SetDefaultPrinter(string printerName);

Now on button click or on form load just change the printer you want to use while printing and then change it back to the one before.

//Set the default printer. I have set it as my Adobe PDF printer
SetDefaultPrinter("Adobe PDF");
Currently rated 5.0 by 1 person

Shoutdown/Logoff/Hibernate/Stand By - Use CODE to do 'em all

12. June 2009 17:32

C# Code Snippets 

Step 1: Add the following line to use the namespace. This is necessary as we need to use the User32.dll with DLLImport attribute.

using System.Runtime.InteropServices;

Step 2: Now add the below line to your code to use the methods from the User32.dll

public static extern void LockWorkStation();
public static extern int ExitWindowsEx(int uFlags, int dwReason);

Step 3: Once you complete the above two steps, you can now call the methods on button click or after some or with some particular event or the way you like.

LockWorkStation(); //Locks the workstation, Equivalent to WIN+L
ExitWindowsEx(0, 0)//Shutdowns the machine 
Application.SetSuspendState(PowerState.Suspend, true, true)  //Put the machine in stand-by mode
Application.SetSuspendState(PowerState.Hibernate, true, true); // Hibernates the system
 No Rating