• Unfortunately, we have experienced significant hard drive damage that requires urgent maintenance and rebuilding. The forum will be a state of read only until we install our new drives and rebuild all the configurations needed. Please follow our Facebook page for updates, we will be back up shortly! (The forum could go offline at any given time due to the nature of the failed drives whilst awaiting the upgrades.) When you see an Incapsula error, you know we are in the process of migration.

[C#] An easy Configuration class

Moderator
Staff member
Moderator
Joined
Feb 22, 2008
Messages
2,404
Reaction score
724
I designed this class to make the process of reading configuration from ini files a little bit faster and easier. First of all you need to download the iniParser library:

The configuration class:
Code:
public class Configuration
    {


        IniData parsedData;


        Dictionary<string, string> settings;


        public Configuration(string iniPath)
        {
            var parser = new FileIniDataParser();
            parsedData = parser.LoadFile(Path.Combine(Environment.CurrentDirectory, iniPath));
            settings = new Dictionary<string, string>();


            // populate configs
            var sections = parsedData.Sections.GetEnumerator();
            while (sections.MoveNext())
            {
                var current = sections.Current;
                var sectionName = current.SectionName;
                // getting all the keys for that section.
                var keys = current.Keys.GetEnumerator();
                while (keys.MoveNext())
                {
                    var currentKey = keys.Current;
                    var keyName = currentKey.KeyName;
                    var keyValue = currentKey.Value;


                    this.settings.Add(string.Format("{0}.{1}", sectionName, keyName), keyValue);
                }
            }
        }


        public string this[string name]
        {
            get
            {
                string result = null;
                var success = this.settings.TryGetValue(name, out result);
                if (success)
                {
                    return result;
                }
                else
                {
                    return null;
                }
            }
        }
    }

To use it, simple create a new instance of the Configuration class passing in the constructor the config file path.
Assuming this is your ini file:
Code:
[section]
key1 = ragezone
To read its very simple, just do:

Code:
var key1 = configuration["section.key1"];
Remembering the names are CASE-SENSITIVE.
 
• ♠️​ ♦️ ♣️ ​♥️ •
Joined
Mar 25, 2012
Messages
909
Reaction score
464
Windows already offers functions to handle INI files inside of the kernel32.dll, no extern library neccessary.
PHP:
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace _modiX.Utilities
{
	/// <summary>
	/// Create a New INI file to store or load data
	/// </summary>
	public class IniFile
	{
		private string path;

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

		/// <summary>
		/// INI file Constructor.
		/// </summary>
		/// <PARAM name="INIPath"></PARAM>
		public IniFile(string iniPath)
		{
			this.path = iniPath;
		}

		/// <summary>
		/// Write Data to the INI File
		/// </summary>
		/// <param name="section"></param>
		/// Section name
		/// <param name="key"></param>
		/// Key Name
		/// <param name="value"></param>
		/// Value Name
		public void Write(string section, string key, string value)
		{
			WritePrivateProfileString(section, key, value, this.path);
		}

		/// <summary>
		/// Write all data to INI file.
		/// </summary>
		/// <param name="data">Selection-Key-Value - Collection.</param>
		public void WriteAll(Dictionary<string, Dictionary<string, string>> data)
		{
			foreach (string selection in data.Keys)
			{
				foreach (string key in data[selection].Keys)
				{
					this.Write(selection, key, data[selection][key]);
				}
			}
		}

		/// <summary>
		/// Read Data Value From the Ini File
		/// </summary>
		/// <param name="section"></param>
		/// <param name="key"></param>
		/// <returns></returns>
		public string Read(string section, string key)
		{
			StringBuilder temp = new StringBuilder(255);
			int i = GetPrivateProfileString(section, key, "", temp, 255, this.path);
			return temp.ToString();
		}

		/// <summary>
		/// Read all data from INI file. 
		/// </summary>
		/// <returns>Selection-Key-Value - Collection.</returns>
		public Dictionary<string, Dictionary<string, string>> ReadAll()
		{
			Dictionary<string, Dictionary<string, string>> result = new Dictionary<string, Dictionary<string, string>>();
			/*
			 * Try to read the content of a simle INI file
			 */
			List<string> selections = this.getSelections();
			foreach (string selection in selections)
			{
				/*
				 * Get the keys
				 */
				List<string> keys = this.getKeys(selection);
				foreach (string key in keys)
				{
					/*
					 * Now store the content
					 */
					if (!result[selection].ContainsKey(key))
					{
						result[selection].Add(key, "");
					}
					result[selection][key] = this.Read(selection, key);
				}
			}

			return result;
		}

		/// <summary>
		/// Shows the Path.
		/// </summary>
		/// <returns>Path to INI file.</returns>
		public override string ToString()
		{
			return this.path;
		}

		private List<string> getKeys(string selection)
		{
			StringBuilder temp = new StringBuilder(32768);
			GetPrivateProfileString(selection, null, null, temp, 32768, this.path);
			List<string> result = new List<string>(temp.ToString().Split('\0'));
			result.RemoveRange(result.Count - 2, 2);
			return result;
		}

		private List<string> getSelections()
		{
			StringBuilder temp = new StringBuilder(65536);
			GetPrivateProfileString(null, null, null, temp, 65536, this.path);
			List<string> result = new List<string>(temp.ToString().Split('\0'));
			result.RemoveRange(result.Count - 2, 2);
			return result;
		}
	}
}

My little INI file class offers even more methods for a faster whole read/write poop.


But tbh imo using INI files is such outdated. I would rather build a domain tier configuration class and serialize / de-serialize it with the XMLSerializer.
 
Moderator
Staff member
Moderator
Joined
Feb 22, 2008
Messages
2,404
Reaction score
724
Well, if you want to make a cross-plataform then you shouldn't use windows apis. Since that library is mono compatible, I think it is way superior than a simple GetPrivateProfileString :):
 
• ♠️​ ♦️ ♣️ ​♥️ •
Joined
Mar 25, 2012
Messages
909
Reaction score
464
Well, if you want to make a cross-plataform then you shouldn't use windows apis. Since that library is mono compatible, I think it is way superior than a simple GetPrivateProfileString :):

Indeed, for cross platforms yours is better. But as long as you do windows programming, using a third party library when windows offers this for you already would be dump.

Both is right ^^.
But on your position I would extend it for more features, like my class does. If you want you can even adapt my one and make it mono compatible. :p haha
 
Back
Top