Read/Write settings to INI File using C#

21. October 2009 18:12

C# Code Snippets  16 Comments

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;
        
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,
        string key,
        string val,
        string filePath);

        [DllImport("kernel32")]
        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.8 by 12 people

Comments (16)

Nadeem Shaikh Nadeem Shaikh
9/6/2011 12:10:13 PM #

Thanks a lot

Al Al
9/13/2011 6:21:58 PM #

good stuff ! Thanks

Alex Alex
12/29/2011 5:06:15 PM #

I can't read key. (return void string) But writing is OK.

donnovan donnovan
4/3/2012 12:59:00 PM #

thanx a million

robert robert
5/23/2012 1:05:48 PM #

A small thing is missing ... using System.Runtime.InteropServices; But nice code !

temalaner temalaner
6/7/2012 5:37:50 PM #

// write data setting button_Click private void button1_Click(object sender, EventArgs e) { INIFile inif = new INIFile("C:\\config.ini"); inif.Write("Database", "Devs", "sa"); inif.Write("Database", "Deva", "11"); inif.Write("Database", "Devb", "467"); } // read data setting button_Click private void button2_Click(object sender, EventArgs e) { INIFile inif = new INIFile("C:\\config.ini"); textBox1.Text = inif.Read("Database", "Devs"); /// output display textbox "sa" }

Felipe Vieira Felipe Vieira
6/13/2012 7:34:38 PM #

Mine is not working.. It's showing [quote]Error 1 Method must have a return type c:\documents and settings\felipe\meus documentos\visual studio 2010\Projects\LoginScreen\LoginScreen\Server.cs 27 12 LoginScreen[/quote] [quote]public INIFile(string filePath) { this.filePath = filePath; }[/quote] I am starting with C# ^^ What can i do?

amit amit
6/19/2012 12:20:21 PM #

well done...!! nice, well explained.. :)

amit amit
6/19/2012 12:30:18 PM #

Thnsk a ton!! well done... :)

Federico Federico
8/14/2012 2:17:05 PM #

This is a constructor method. It should have the same name as the class. Check if you declared the class as INIFile

Vsoler Vsoler
8/23/2012 8:15:37 PM #

I compile this class as module: using System; using System.IO; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace ini_wr { public class INIFile { private string filePath; [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] 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; } } } } and call it from .exe: using System; using System.IO; using ini_wr; namespace ini_test { class Test { static void Main(string[] args) { // Console.WriteLine("Pishem velichinu:"); INIFile inif = new INIFile(@"D:\DevPlace\sharp\config.ini"); inif.Write("Database", "Devs", "sa"); inif.Write("Database", "Deva", "11"); inif.Write("Database", "Devb", "467"); inif.Write("Korova", "moloko", "19"); inif.Write("Korova", "moloko2", "21"); inif.Write("Stegocefall", "roga", "2"); inif.Write("Stegocefall", "roga0", "1"); } } }

Vsoler Vsoler
8/23/2012 8:22:11 PM #

I compile module in CMD.EXE: >csc /target:module /out:module_name.win file_name.cs You can assign any file extension, on your preference (I use ini_wr.lpt) Don`t forget add PATH value for csc and restart the computer.

Vsoler Vsoler
8/23/2012 8:32:22 PM #

Reading: using System; using System.IO; using ini_wr; namespace ini_test { class Test { static void Main(string[] args) { // Console.WriteLine("Read value:"); INIFile inif = new INIFile(@"D:\DevPlace\sharp\config.ini"); string a1 = inif.Read("Database", "Devs"); Console.WriteLine(a1); string a2 = inif.Read("Database", "Deva"); Console.WriteLine(a2); string a3 = inif.Read("Database", "Devb"); Console.WriteLine(a3); string a4 = inif.Read("Korova", "moloko"); Console.WriteLine(a4); string a5 = inif.Read("Korova", "moloko2"); Console.WriteLine(a5); string a6 = inif.Read("Stegocefall", "roga"); Console.WriteLine(a6); string a7 = inif.Read("Stegocefall", "roga0"); Console.WriteLine(a7); } } } maybe too long :)

Devendra Devendra
10/16/2014 10:07:57 AM #

Hi, I used this code, thanks for that. but there is a problem with me, actually my ini file located in C:\Windows\abc.ini so there for I cann't able to write values in it. if I put file in other drive like D:\abc.ini then It is write values. plz help. Thanks in Advance.

Mario Mario
3/5/2015 2:28:01 PM #

Devendra your problem is that you are trying to write in a location that requires Admin privileges, so you need to start your app with Admin privileges, or make your program request them, see here how: http://www.aneef.net/2009/06/29/request-uac-elevation-for-net-application-managed-code/ Also just in case anyone is interested I made a library that helps me process INI files but without using the Kernel32.dll, just a pure .NET approach, you can find it here: https://github.com/MarioZ/MadMilkman.Ini

not working utf8 ini not working utf8 ini
11/4/2015 7:44:32 AM #

not working with utf8 format. Help me!

Add Comment

Visit blogadda.com to discover Indian blogs Computers Blogs