How to Read and Write INI Files in C#

Muhammad Zeeshan Feb 02, 2024
  1. What Is the INI File in C#
  2. Use WritePrivateProfileString to Save New and Modified Settings in an INI File in C#
  3. Use ReadPrivateProfileString to Read Data From an INI File in C#
  4. Read and Write INI Files in C#
How to Read and Write INI Files in C#

This tutorial teaches to read and write INI files in C#.

What Is the INI File in C#

Initializing files, often called INI files, are text files for storing program configuration information. The .NET framework does not natively support INI files.

You can utilize Windows API methods using Platform Invocation Services to write to and read from the files. This tutorial will construct a class representing INI files and manipulate them with Windows API operations.

To operate with INI files, we’ll need two Windows API functions, WritePrivateProfileString and ReadPrivateProfileString.

Use WritePrivateProfileString to Save New and Modified Settings in an INI File in C#

In an INI file, WritePrivateProfileString saves new and modified settings. The structure is as follows.

bool WritePrivateProfileString(string name, string key, string value, string filepath);

The function returns a Boolean result of true if the writing succeeds and false if the write fails. The following are the parameters.

  1. The section’s name to be written is specified by name.
  2. The name of the key to be set is specified by key.
  3. The value for the key is specified by value.
  4. The filepath holds the location of the INI file to be updated.

Use ReadPrivateProfileString to Read Data From an INI File in C#

ReadPrivateProfileString reads data from an INI file. The function reads single values, all key names from a section, or all section names depending on its application.

int GetPrivateProfileString(string name, string key, string default, StringBuilder ReturnedVal,
                            int maxsize, string filepath);

The number of characters in the returned value is returned as an unsigned integer by the function. The following are the parameters.

  1. The section’s name to be read is specified by name. If this is set to null, all section names will be returned.
  2. The name of the key to be read is specified by key. The returned value will include the names of the keys in the given section if set to null while the name is not null.
  3. If the key isn’t present, default specifies a default value to return.
  4. ReturnedVal receives a string that serves as a buffer. The operation’s result is written into the buffer, modifying the string’s value.
  5. The maximum size of the string that will be returned in ReturnedVal is specified by maxsize. This should be the same as the buffer size. If the value read from the INI file is longer than ReturnedVal, it will be reduced.
  6. The location and name of the INI file to be read are specified by filepath. This file has to be present.

Read and Write INI Files in C#

Let’s make a class to hold the structures of the Windows API functions we’ll be using now that we’ve seen their structures.

Add the following libraries.

using System;
using System.IO;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;

Create a new class named ReadWriteINIfile and use the following class code. Because there is no access modifier for the class itself, it will have an internal scope.

The IniFile class will access the API functions without exposing them to the public.

public class ReadWriteINIfile {
  [DllImport("kernel32")]
  private static extern long WritePrivateProfileString(string name, 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);
}

We can now construct the ReadWriteINIfile class, allowing us to read INI files without knowing the API operations.

Add the following code to the class to create the constructer.

public ReadWriteINIfile(string inipath) {
  path = inipath;
}

WritePrivateProfileString is used to populate an INI file with values. Three arguments are used in the code below to accept the section and key names and the value to save.

In the call to WritePrivateProfileString, these values are combined with the filename passed to the constructer.

public void WriteINI(string name, string key, string value) {
  WritePrivateProfileString(name, key, value, this.path);
}

The arguments to ReadINI are the name and key to read. The first line of the code above defines the string and sets its value to several spaces equal to its maximum length.

The GetPrivateProfileString function receives this string as a buffer to be populated. Use the code below.

public string ReadINI(string name, string key) {
  StringBuilder sb = new StringBuilder(255);
  int ini = GetPrivateProfileString(name, key, "", sb, 255, this.path);
  return sb.ToString();
}

Full source code:

using System;
using System.IO;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;

namespace Test {
  class Program {
    static void Main(string[] args) {}
  }
  public class ReadWriteINIfile {
    [DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string name, 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 string path;

    public ReadWriteINIfile(string inipath) {
      path = inipath;
    }
    public void WriteINI(string name, string key, string value) {
      WritePrivateProfileString(name, key, value, this.path);
    }
    public string ReadINI(string name, string key) {
      StringBuilder sb = new StringBuilder(255);
      int ini = GetPrivateProfileString(name, key, "", sb, 255, this.path);
      return sb.ToString();
    }
  }
}
Muhammad Zeeshan avatar Muhammad Zeeshan avatar

I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I'm a senior in an undergraduate program for a bachelor's degree in Information Technology.

LinkedIn