NEWS

[C#] Chia sẽ class INIHelper dùng để ghi và đọc file config INI

[C#] Chia sẽ class INIHelper dùng để ghi và đọc file config INI
Đăng bởi: Thảo Meo - Lượt xem: 4541 08:31:57, 01/12/2020C#   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẻ gởi đến các bạn class INIHelper.cs dùng để ghi vào đọc file config trong lập trình C# Winform.

[C#] INIHelper Read and Write Config

Định dạng INI (files với đuôi .ini) là một định dạng lưu trữ dữ liệu dạng plain-text (văn bản minh bạch, rõ ràng) được sử dụng chủ yếu trong Microsoft Windows để lưu trữ cấu hình. Nó cũng được sử dụng rộng rãi trên nhiều ứng dụng khác.

Để ghi file cấu hình, các bạn có thể sử dụng nhiều định dạng để lưu thông tin cấu hình phổ biến như: XML, JSON, INI, TXT...

Trong đó tập tin INI dùng để lưu cấu hình các bạn thường thấy rất phổ biến.

Nếu bạn nào có sử dụng PHP thì các bạn thấy file config của PHP là một tập tin INI với tên php.ini

Hình ảnh file cấu hình INI C#:

config_file_ini_csharp

File INIHelper.cs C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConfigHelper
{
	namespace Exceptions
	{
		class InvalidInputException : System.Exception { }
		class ValueDoesntExistException : System.Exception { }
		class KeyDoesntExistException : System.Exception { }
	}
	public class INIHelper
    {	
		System.Collections.Hashtable Keys;
		System.Collections.Hashtable Values;
		public INIHelper()
		{
			Keys = new System.Collections.Hashtable();
			Values = new System.Collections.Hashtable();
		}

		public INIHelper(System.IO.TextReader tr)
		{
			Keys = new System.Collections.Hashtable();
			Values = new System.Collections.Hashtable();
			Parse(tr);
		}
		public string GetValue(string Key, string ValueName)
		{
			System.Collections.Hashtable KeyTable = (System.Collections.Hashtable)Keys[Key];
			if (KeyTable != null)
			{
				if (KeyTable.ContainsKey(ValueName))
				{
					return (string)KeyTable[ValueName];
				}
				else
				{
					throw new Exceptions.ValueDoesntExistException();
				}

			}
			else
			{
				throw new Exceptions.KeyDoesntExistException();
			}
		}
		public string GetValue(string ValueName)
		{
			if (Values.ContainsKey(ValueName))
			{
				return (string)Values[ValueName];
			}
			else
			{
				throw new Exceptions.ValueDoesntExistException();
			}
		}
		bool KeyExists(string KeyName)
		{
			return Keys.Contains(KeyName);
		}
		bool ValueExists(string KeyName, string ValueName)
		{
			System.Collections.Hashtable KeyTable = (System.Collections.Hashtable)Keys[KeyName];
			if (KeyTable != null)
			{
				return KeyTable.Contains(ValueName);
			}
			else
			{
				throw new Exceptions.KeyDoesntExistException();
			}
		}
		bool ValueExists(string ValueName)
		{
			return Values.Contains(ValueName);
		}
		public void SetValue(string Key, string ValueName, string Value)
		{
			System.Collections.Hashtable KeyTable = (System.Collections.Hashtable)Keys[Key];
			if (KeyTable != null)
			{
				KeyTable[ValueName] = Value;
			}
			else
			{
				throw new Exceptions.KeyDoesntExistException();
			}
		}
		public void SetValue(string ValueName, string Value)
		{
			Values[ValueName] = Value;
		}
		public void AddKey(string NewKey)
		{
			System.Collections.Hashtable New = new System.Collections.Hashtable();
			Keys[NewKey] = New;
		}
		public void Save(System.IO.TextWriter sw)
		{
			System.Collections.IDictionaryEnumerator Enumerator = Values.GetEnumerator();
			
			sw.WriteLine("; The values in this group");
			while (Enumerator.MoveNext())
			{
				sw.WriteLine("{0} = {1}", Enumerator.Key, Enumerator.Value);
			}
			sw.WriteLine("; This is where the keys begins");
			Enumerator = Keys.GetEnumerator();
			while (Enumerator.MoveNext())
			{
				System.Collections.IDictionaryEnumerator Enumerator2nd = ((System.Collections.Hashtable)Enumerator.Value).GetEnumerator();
				sw.WriteLine("[{0}]", Enumerator.Key);
				while (Enumerator2nd.MoveNext())
				{
					sw.WriteLine("{0} = {1}", Enumerator2nd.Key, Enumerator2nd.Value);
				}
			}
		}
		private void Parse(System.IO.TextReader sr)
		{
			System.Collections.Hashtable CurrentKey = null;
			string Line, ValueName, Value;
			while (null != (Line = sr.ReadLine()))
			{
				int j, i = 0;
				while (Line.Length > i && Char.IsWhiteSpace(Line, i)) i++;
				if (Line.Length <= i)
					continue;
				if (Line[i] == ';')
					continue;
				if (Line[i] == '[')
				{
					string KeyName;
					j = Line.IndexOf(']', i);
					if (j == -1)
						throw new Exceptions.InvalidInputException();

					KeyName = Line.Substring(i + 1, j - i - 1).Trim();

					if (!Keys.ContainsKey(KeyName))
					{
						this.AddKey(KeyName);
					}
					CurrentKey = (System.Collections.Hashtable)Keys[KeyName];
					while (Line.Length > ++j && Char.IsWhiteSpace(Line, j)) ;
					if (Line.Length > j)
					{
						if (Line[j] != ';')
							throw new Exceptions.InvalidInputException();
					}
					continue;
				}
				
				j = Line.IndexOf('=', i);
				if (j == -1)
					throw new Exceptions.InvalidInputException();
				ValueName = Line.Substring(i, j - i).Trim();
				if ((i = Line.IndexOf(';', j + 1)) != -1)
					Value = Line.Substring(j + 1, i - (j + 1)).Trim();
				else
					Value = Line.Substring(j + 1).Trim();
				if (CurrentKey != null)
				{
					CurrentKey[ValueName] = Value;
				}
				else
				{
					Values[ValueName] = Value;
				}
			}
		}
	}
}

Cách sử dụng ghi và đọc file cấu hình INI c#:

using System;
using System.IO;
using System.Text;



namespace ConfigHelper
{
    class Program
    {
        static void Main(string[] args)
        {
			Console.OutputEncoding = Encoding.UTF8;
			var conf = new INIHelper();
			//write value
			conf.AddKey("Person");
			conf.AddKey("Language");
			conf.SetValue("Person", "Name", "Nguyễn Thảo");
			conf.SetValue("Person", "Address", "Bà Rịa Vũng Tàu");
			conf.SetValue("Person", "Age", "31");
			conf.SetValue("Language", "C#", "No");
			conf.SetValue("Language", "VB.NET", "No");
			conf.SetValue("Language", "Java", "Yes");
			conf.SetValue("Language", "Python", "Yes");
			conf.SetValue("username", "ThaoMeo");
			conf.SetValue("password", "123456");
			StreamWriter sw = new StreamWriter("conf.ini");
			conf.Save(sw);
			sw.Close();

			//Read value
			StreamReader sr = new StreamReader("conf.ini");
			var conf2 = new INIHelper(sr);
			sr.Close();
			Console.WriteLine(conf2.GetValue("username"));
			Console.WriteLine(conf2.GetValue("password"));
			Console.WriteLine(conf2.GetValue("Language", "C#"));
			Console.WriteLine(conf2.GetValue("Person", "Name"));
			Console.Read();
		}
    }
}

Kết quả khi chạy hàm trên ta được kết quả như hình bên dưới:

conifg_csharp

Thanks for watching!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Chia sẽ class INIHelper dùng để ghi và đọc file config INI
Đăng bởi: Thảo Meo - Lượt xem: 4541 08:31:57, 01/12/2020C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.