PageRenderTime 40ms CodeModel.GetById 33ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/IniUtility.cs

http://quick-fwknop-ssh-launcher.googlecode.com/
C# | 185 lines | 117 code | 12 blank | 56 comment | 14 complexity | 0308fc2164d656002bafd94d519ee3fa MD5 | raw file
  1using System;
  2using System.Collections.Generic;
  3using System.Linq;
  4using System.Text;
  5using System.Text.RegularExpressions;
  6using System.IO;
  7
  8namespace Quick_Knock
  9{
 10    /// <summary>
 11    /// Read/Write .ini Files
 12    /// 
 13    /// Version 1, 2009-08-15
 14    /// http://www.Stum.de
 15    /// </summary>
 16    /// <remarks>
 17    /// It supports the simple .INI Format:
 18    /// 
 19    /// [SectionName]
 20    /// Key1=Value1
 21    /// Key2=Value2
 22    /// 
 23    /// [Section2]
 24    /// Key3=Value3
 25    /// 
 26    /// You can have empty lines (they are ignored), but comments are not supported
 27    /// Key4=Value4 ; This is supposed to be a comment, but will be part of Value4
 28    /// 
 29    /// Whitespace is not trimmed from the beginning and end of either Key and Value
 30    /// 
 31    /// Licensed under WTFPL
 32    /// http://sam.zoy.org/wtfpl/
 33    /// </remarks>
 34    public class IniFile
 35    {
 36        private Dictionary<string, Dictionary<string, string>> _iniFileContent;
 37        private readonly Regex _sectionRegex = new Regex(@"(?<=\[)(?<SectionName>[^\]]+)(?=\])");
 38        private readonly Regex _keyValueRegex = new Regex(@"(?<Key>[^=]+)=(?<Value>.+)");
 39
 40        public IniFile() : this(null){}
 41
 42        public IniFile(string filename)
 43        {
 44            _iniFileContent = new Dictionary<string, Dictionary<string, string>>();
 45            if (filename != null) Load(filename);
 46        }
 47
 48        /// <summary>
 49        /// Get a specific value from the .ini file
 50        /// </summary>
 51        /// <param name="sectionName"></param>
 52        /// <param name="key"></param>
 53        /// <returns>The value of the given key in the given section, or NULL if not found</returns>
 54        public string GetValue(string sectionName, string key)
 55        {
 56            if (_iniFileContent.ContainsKey(sectionName) && _iniFileContent[sectionName].ContainsKey(key))
 57                return _iniFileContent[sectionName][key];
 58            else
 59                return null;
 60        }
 61
 62        /// <summary>
 63        /// Set a specific value in a section
 64        /// </summary>
 65        /// <param name="sectionName"></param>
 66        /// <param name="key"></param>
 67        /// <param name="value"></param>
 68        public void SetValue(string sectionName, string key, string value)
 69        {
 70            if(!_iniFileContent.ContainsKey(sectionName)) _iniFileContent[sectionName] = new Dictionary<string, string>();
 71            _iniFileContent[sectionName][key] = value;
 72        }
 73
 74        /// <summary>
 75        /// Get all the Values for a section
 76        /// </summary>
 77        /// <param name="sectionName"></param>
 78        /// <returns>A Dictionary with all the Key/Values for that section (maybe empty but never null)</returns>
 79        public Dictionary<string, string> GetSection(string sectionName)
 80        {
 81            if (_iniFileContent.ContainsKey(sectionName))
 82                return new Dictionary<string, string>(_iniFileContent[sectionName]);
 83            else
 84                return new Dictionary<string, string>();
 85        }
 86
 87        /// <summary>
 88        /// Set an entire sections values
 89        /// </summary>
 90        /// <param name="sectionName"></param>
 91        /// <param name="sectionValues"></param>
 92        public void SetSection(string sectionName, IDictionary<string, string> sectionValues)
 93        {
 94            if (sectionValues == null) return;
 95            _iniFileContent[sectionName] = new Dictionary<string, string>(sectionValues);
 96        }
 97
 98
 99        /// <summary>
100        /// Load an .INI File
101        /// </summary>
102        /// <param name="filename"></param>
103        /// <returns></returns>
104        public bool Load(string filename)
105        {
106            if (File.Exists(filename))
107            {
108                try
109                {
110                    var content = File.ReadAllLines(filename);
111                    _iniFileContent = new Dictionary<string, Dictionary<string, string>>();
112                    string currentSectionName = string.Empty;
113                    foreach (var line in content)
114                    {
115                        Match m = _sectionRegex.Match(line);
116                        if (m.Success)
117                        {
118                            currentSectionName = m.Groups["SectionName"].Value;
119                        }
120                        else
121                        {
122                            m = _keyValueRegex.Match(line);
123                            if (m.Success)
124                            {
125                                string key = m.Groups["Key"].Value;
126                                string value = m.Groups["Value"].Value;
127
128                                Dictionary<string, string> kvpList;
129                                if (_iniFileContent.ContainsKey(currentSectionName))
130                                {
131                                    kvpList = _iniFileContent[currentSectionName];
132                                }
133                                else
134                                {
135                                    kvpList = new Dictionary<string, string>();
136                                }
137                                kvpList[key] = value;
138                                _iniFileContent[currentSectionName] = kvpList;
139                            }
140                        }
141                    }
142                    return true;
143                }
144                catch
145                {
146                    return false;
147                }
148
149            }
150            else
151            {
152                return false;
153            }
154        }
155
156        /// <summary>
157        /// Save the content of this class to an INI File
158        /// </summary>
159        /// <param name="filename"></param>
160        /// <returns></returns>
161        public bool Save(string filename)
162        {
163            var sb = new StringBuilder();
164            if (_iniFileContent != null)
165            {
166                foreach (var sectionName in _iniFileContent)
167                {
168                    sb.AppendFormat("[{0}]\r\n", sectionName.Key);
169                    foreach (var keyValue in sectionName.Value)
170                    {
171                        sb.AppendFormat("{0}={1}\r\n", keyValue.Key, keyValue.Value);
172                    }
173                }
174            }
175            try
176            {
177                File.WriteAllText(filename, sb.ToString());
178                return true;
179            } catch
180            {
181                return false;
182            }
183        }
184    }
185}