view IniFileReader.cs @ 0:fbde5e1920ba

Re #6 (Ini parsing library) - Initial commit of IBBoard Ini parsing
author IBBoard <dev@ibboard.co.uk>
date Thu, 08 Jan 2009 20:33:56 +0000
parents
children f9444f1786cd
line wrap: on
line source

// This file (IniFileReader.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.IO;
using System.Text;

namespace IBBoard.Ini
{
	public class IniFileReader
	{
		public static IniFile ReadFile(string path)
		{
			return ReadFile(new FileInfo(path));
		}
		
		public static IniFile ReadFile(FileInfo file)
		{
			if (!file.Exists)
			{
				throw new FileNotFoundException(file.FullName+" did not exist and could not be read");
			}
			
			IniFile iniFile = new IniFile();
			LoadDataFromFile(file, iniFile);			
			return iniFile;
		}
		
		private static void LoadDataFromFile(FileInfo file, IniFile iniFile)
		{
			StreamReader stream = file.OpenText();
			
			try
			{
				LoadDataFromStream(iniFile, stream);
			}
			finally
			{
				stream.Close();
			}
		}
		
		private static void LoadDataFromStream(IniFile iniFile, StreamReader stream)
		{
			StringBuilder sectionStringBuilder = new StringBuilder();
			
			while (!stream.EndOfStream)
			{
				string line = stream.ReadLine().Trim();
				
				if (IniSectionParser.IsLineStartOfNewSection(line))
				{
					String currSection = sectionStringBuilder.ToString();
					
					if (IniSectionParser.IsStringAnIniSection(currSection))
					{
						IniSection section = IniSectionParser.CreateSection(currSection);
						iniFile.AddSection(section);
					}
					
					sectionStringBuilder.Length = 0;
				}
				
				sectionStringBuilder.Append(line);
				sectionStringBuilder.Append("\n");
			}
		}
		
		
	}
}