Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

[Tips] How to read write Ini File in C#

Thursday, 25 June 2015
|
Read: Completed in minutes

[Tips] How to read write Ini File in C#


How to Read and Write INI Files in C#

INI files are a simple and widely used format for storing configuration settings. They consist of sections, keys, and values, separated by brackets, equal signs, and newlines. For example, an INI file might look like this:
How to read write Ini File in C#


[General]
Name=John
Age=25
[Preferences]
Color=Blue
Font=Arial

In this article, we will show you how to read and write INI files in C# using the Windows API functions WritePrivateProfileString and GetPrivateProfileString. These functions are defined in the kernel32.dll library, which we can access using the Platform Invoke (P/Invoke) feature of .NET.

To use these functions, we need to declare them in our code using the DllImport attribute. We also need to specify the character set, the entry point, and the parameters of each function. For example:

 
	using System.Runtime.InteropServices;
	[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]	
	static extern long WritePrivateProfileString(string section, string key, string value, string filePath);
	
	[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
	static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);
	

The WritePrivateProfileString function writes a value to a specified key in a specified section of an INI file. The parameters are:

•  section: The name of the section to write to.

•  key: The name of the key to write to.

•  value: The value to write.

•  filePath: The path of the INI file.

The GetPrivateProfileString function reads a value from a specified key in a specified section of an INI file. The parameters are:

•  section: The name of the section to read from.

•  key: The name of the key to read from.

•  defaultValue: The default value to return if the key is not found.

•  retVal: A StringBuilder object that receives the value.

•  size: The maximum number of characters to copy to the retVal object.

•  filePath: The path of the INI file.

To use these functions in our code, we can create a helper class that wraps them in more convenient methods. For example:

 
	using System.IO;
	using System.Text; 
	public class IniFile {
		private string filePath; 
	
		public IniFile(string filePath) {
			this.filePath = filePath;
			public void Write(string section, string key, string value) {
				WritePrivateProfileString(section, key, value, filePath);
			}
		}
		
		public string Read(string section, string key) {
			StringBuilder retVal = new StringBuilder(255);
			GetPrivateProfileString(section, key, "", retVal, 255, filePath);
			return retVal.ToString();
		} 
		
		public bool Exists() { 
			return File.Exists(filePath); 
		}
		
	}

With this class, we can easily read and write INI files in C#. For example:
 
	IniFile ini = new IniFile("settings.ini");


 
	// Write some values
	ini.Write("General", "Name", "John");
	ini.Write("General", "Age", "25");
	ini.Write("Preferences", "Color", "Blue");
	ini.Write("Preferences", "Font", "Arial");

 
	// Read some values
	string name = ini.Read("General", "Name"); 
	string age = ini.Read("General", "Age"); 
	string color = ini.Read("Preferences", "Color"); 
	string font = ini.Read("Preferences", "Font"); 


We can also check if the INI file exists using the Exists method. For example:
 
	if (ini.Exists()) { 
		Console.WriteLine("INI file found."); 
	} else { 
		Console.WriteLine("INI file not found.");
	}


This is how we can read and write INI files in C# using the Windows API functions. For more information and examples on these functions, you can refer to these sources

•  #CSharp

•  #INIFiles

•  #WindowsAPI

•  #PInvoke

•  #Configuration

•  #Settings

•  #Programming

•  #Coding

•  #Tutorial

•  #HowTo

•  #DotNet

•  #Kernel32

•  #WritePrivateProfileString

•  #GetPrivateProfileString

•  #CodeExample style="color: red;">What's INI file?

  • INI file is common system config files. 
  • INI files are text files that store name=value pairs.
  • INI files can be used to save basic user settings easily. 

This topic will be focus to how to read, write INI files in CSharp.

 


I'm using two functions: Read, Write INI files


Read function:
- Using GetPrivateProfileStringAPI for get key values in INI files
- Using StringBuilder to stored value from file.

Write function:Using WritePrivateProfileString API for write key values in INI files

Source Code



 /* ************************************************************************
       * Author: Vแป‹LH - Zidane (huuvi168@gmail.com)
       * Last Modified: 20141215 
       * clsIniFile.cs
       * ************************************************************************
       */
      
      using System;
      using System.Collections.Generic;
      using System.Runtime.InteropServices;
      using System.Text;
      
      /* 
       * How to use: clsIniFile
       * 
       * --> Write file 
       * clsIniFile inif = new clsIniFile("D:\\config.ini");
       * inif.Write("Database", "Devs", "sa");
       * 
       * => [Database]
       *    Devs=sa;
       * 
       * --> Read file
       * clsIniFile inif = new clsIniFile("D:\\config.ini");
       * Console.WriteLine("The Value is:" + inif.Read("Database", "Devs"));
       * => sa
       * 
       */
      
      namespace IniFileCommons
      {
          public class clsIniFile
          {
              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 clsIniFile(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; }
              }
          }
      }
      



Leave your comment for How to read Write Ini File In CSharp,
If you have any feedback with above code!
Thank you for reading this post. I hope you found it helpful and easy to follow. If you have any feedback or questions about Ini File Manipulation with C# , please share them in the comments below. I would love to hear from you and discuss this topic further
✋✋✋✋  Webzone Tech Tips, all things Tech Tips for web development  - I am Zidane, See you next time soon ✋✋✋✋

๐Ÿ™‡๐Ÿผ๐Ÿ™‡๐Ÿผ Your Feedback Is Valuable and Helpful to Us - Webzone, all things Tech Tips web development Zidane
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com