Use INI file in C# to save and retrive values

INI files are good to store and retrieve values dynamically from applications, but the down side of it, that INI files don’t support Unicode and it’s all in plain text so security is a concern. The other problem is sometimes you need ‘Administrator’ privilege to access the file.

C# Code

create a class:

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

namespace Ini

    public class IniFile
        public string path;

        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);

        /// INIFile Constructor.
        public IniFile(string INIPath)
            path = INIPath;
        /// Write Data to the INI File
        public void IniWriteValue(string Section, string Key, string Value)
            WritePrivateProfileString(Section, Key, Value, this.path);

        /// Read Data Value From the Ini File
        public string IniReadValue(string Section, string Key)
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
            return temp.ToString();


reading values from the INI file

// create an instance
 IniFile ini = new IniFile(Application.StartupPath + @"\config.ini");

// reading the values
           string username = ini.IniReadValue("sftp", "Username");
           string password = ini.IniReadValue("sftp", "Password");
           string remotehost = ini.IniReadValue("sftp", "Remote Host");

writing to the INI file

ini.IniWriteValue("sftp","Remote Host","111.22.334.555")

The INI file looks like below:

;SFTP details - this is a comment in INI
Username = key_value
Password = key_value
Remote Host = 111.22.334.555

Happy coding!