[C#] An easy Configuration class

Results 1 to 4 of 4
  1. #1
    Fuck. SheenBR is offline
    ModeratorRank
    Feb 2008 Join Date
    Jaú, BrazilLocation
    2,433Posts

    [C#] An easy Configuration class

    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: https://github.com/rickyah/ini-parser

    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.


  2. #2
    • ♠️​ ♦️ ♣️ ​♥️ • שเ๒єtгเ๒є is offline
    MemberRank
    Mar 2012 Join Date
    917Posts

    Re: [C#] An easy Configuration class

    Windows already offers functions to handle INI files inside of the kernel32.dll, no extern library neccessary.
    PHP Code:
    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 keystring valstring filePath);
            [
    DllImport("kernel32")]
            private static 
    extern int GetPrivateProfileString(string sectionstring keystring defStringBuilder retValint sizestring 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 sectionstring keystring value)
            {
                
    WritePrivateProfileString(sectionkeyvaluethis.path);
            }

            
    /// <summary>
            /// Write all data to INI file.
            /// </summary>
            /// <param name="data">Selection-Key-Value - Collection.</param>
            
    public void WriteAll(Dictionary<stringDictionary<stringstring>> data)
            {
                foreach (
    string selection in data.Keys)
                {
                    foreach (
    string key in data[selection].Keys)
                    {
                        
    this.Write(selectionkeydata[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 sectionstring key)
            {
                
    StringBuilder temp = new StringBuilder(255);
                
    int i GetPrivateProfileString(sectionkey""temp255this.path);
                return 
    temp.ToString();
            }

            
    /// <summary>
            /// Read all data from INI file. 
            /// </summary>
            /// <returns>Selection-Key-Value - Collection.</returns>
            
    public Dictionary<stringDictionary<stringstring>> ReadAll()
            {
                
    Dictionary<stringDictionary<stringstring>> result = new Dictionary<stringDictionary<stringstring>>();
                
    /*
                 * Try to read the content of a simle INI file
                 */
                
    List<stringselections this.getSelections();
                foreach (
    string selection in selections)
                {
                    
    /*
                     * Get the keys
                     */
                    
    List<stringkeys 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(selectionkey);
                    }
                }

                return 
    result;
            }

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

            private List<
    stringgetKeys(string selection)
            {
                
    StringBuilder temp = new StringBuilder(32768);
                
    GetPrivateProfileString(selectionnullnulltemp32768this.path);
                List<
    stringresult = new List<string>(temp.ToString().Split('\0'));
                
    result.RemoveRange(result.Count 22);
                return 
    result;
            }

            private List<
    stringgetSelections()
            {
                
    StringBuilder temp = new StringBuilder(65536);
                
    GetPrivateProfileString(nullnullnulltemp65536this.path);
                List<
    stringresult = new List<string>(temp.ToString().Split('\0'));
                
    result.RemoveRange(result.Count 22);
                return 
    result;
            }
        }

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


    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.

  3. #3
    Fuck. SheenBR is offline
    ModeratorRank
    Feb 2008 Join Date
    Jaú, BrazilLocation
    2,433Posts

    Re: [C#] An easy Configuration class

    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

  4. #4
    • ♠️​ ♦️ ♣️ ​♥️ • שเ๒єtгเ๒є is offline
    MemberRank
    Mar 2012 Join Date
    917Posts

    Re: [C#] An easy Configuration class

    Quote Originally Posted by SheenBR View Post
    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



Advertisement