view IniSectionParser.cs @ 1:f9444f1786cd

Re #6 - INI parsing library * Add ToString methods * Add types of string and parse to objects instead of parsing to key-value pair * Create method to load INI data from string * Add content of AddSection method
author IBBoard <dev@ibboard.co.uk>
date Sun, 11 Jan 2009 15:37:14 +0000
parents fbde5e1920ba
children 2dde4c1d19d9
line wrap: on
line source

// This file (IniSectionParser.cs) is a part of the IBBoard.Ini library and is copyright 2009 IBBoard.
//
// The file and the library/program it is in are licensed under the GNU LGPL license. Please see COPYING.LGPL for more information and the full license.

using System;
using System.Text.RegularExpressions;

namespace IBBoard.Ini
{
	/// <summary>
	/// The IniSectionParser provides parsing of a single section from an INI file
	/// </summary>
	public class IniSectionParser
	{
		public static bool IsLineStartOfNewSection(string line)
		{
			line = line.Trim();
			return line.StartsWith("[") && line.EndsWith("]");
		}
		
		public static bool IsStringAnIniSection(string potentialSection)
		{
			return Regex.IsMatch(potentialSection, "^\\s*\\[[a-zA-Z0-9]+\\]\\s*\\n", RegexOptions.Multiline);
		}
		
		/// <summary>
		/// Creates an IniSection object from a string. The new line (\n) character is used to determine line breaks.
		/// </summary>
		/// <param name="sectionString">
		/// A <see cref="System.String"/>
		/// </param>
		/// <returns>
		/// A <see cref="IniSection"/>
		/// </returns>
		public static IniSection CreateSection(string sectionString)
		{
			if (!IsStringAnIniSection(sectionString))
			{
				throw new InvalidIniSectionException("Ini section did not start with an INI header");
			}
			
			string[] sectionLines = sectionString.Split('\n');
			string headerLine = sectionLines[0];
			string sectionName = headerLine.Trim().Substring(1, headerLine.Length - 2);
			IniSection section = new IniSection(sectionName);
			int lineCount = sectionLines.Length;
			
			for (int i = 1; i < lineCount; i++)
			{
				IIniLine iniLine = IniLineParser.ParseIniLine(sectionLines[i]);
				section.AddIniLine(iniLine);
			}
			
			return section;
		}
	}
}