/// <summary> /// 创建一个inifile对象,把数据读入内存中,并关闭文件 /// </summary> /// <param name="path">文件路径</param> public NLIniFile(string path) { if (!System.IO.File.Exists(path)) { throw new FileNotFoundException("IniFile not found path={0}", path); } #region Read Ini File StreamReader sr = new StreamReader(path, Encoding.Default); string line; string newSection = ""; Items = new List <IniFileItem>(); while ((line = sr.ReadLine()) != null) { line = line.Trim(); if (line.IndexOf("//") >= 0) //remove commont { line = line.Substring(0, line.IndexOf("//")); } if (line.Length > 0) { if (line[0] == '[') //take as a Section { int start = 0; int end = line.IndexOf(']'); if (end > start) { newSection = line.Substring(start + 1, end - start - 1).Trim(); } } else if (line.IndexOf('=') >= 0) //task as a key { string[] infos = line.Split('='); if (infos.Length == 2) { IniFileItem item = new IniFileItem { Section = newSection, Keyword = infos[0].Trim(), Value = infos[1].Trim() }; Items.Add(item); } } } } sr.Close(); #endregion }
/// <summary> /// IniFileSectionCollection オブジェクトの末尾セクションへアイテムを追加する。 /// </summary> /// <param name="dest">IniFileSectionCollection オブジェクト。</param> /// <param name="name">名前。</param> /// <param name="value">値。</param> private static void AddItemToLastSection( IniFileSectionCollection dest, string name, string value) { Debug.Assert(dest != null && dest.Count > 0); var section = dest[dest.Count - 1]; IniFileItem item = null; try { item = new IniFileItem(name); } catch (Exception ex) { throw new FormatException( "The name of the item (in the section \"" + section.Name + "\") is invalid.", ex); } try { item.Value = value; } catch (Exception ex) { throw new FormatException( "The value of the item (\"" + name + "\" in the section \"" + section.Name + "\") is invalid.", ex); } try { dest[dest.Count - 1].Items.Add(item); } catch (Exception ex) { throw new FormatException( "The item (\"" + name + "\" in the section \"" + section.Name + "\") is duplicated.", ex); } }