- [DEVEXPRESS] Chia sẻ source code cách tạo biểu đồ sơ đồ tổ chức công ty Org Chart trên Winform C#
- [C#] Hướng dẫn tạo Auto Number trên Datagridview winform
- [DATABASE] Hướng dẫn tạo Procedure String Split in Mysql
- [C#] Thiết lập dấu (,) hay dấu (.) ở định dạng số đúng với định dạng số Việt Nam
- [C#] Chia sẻ source code Game Spin Lucky Wheel
- [C#] Hướng dẫn Encode and Decode HTML
- Danh sách tài khoản ChatGPT miễn phí - Hướng dẫn tạo tài khoản Chat Open AI GPT tại Việt Nam
- [C#] Hướng dẫn thay đổi giao diện ứng dụng Winform theo giao diện của Windows
- [VB.NET] Hiệu ứng Acrylic, Mica, Tabbed Blur Effect trên Winform
- [DEVEXPRESS] Hướng dẫn sử dụng HTML Template trên Combobox Edit
- [C#] Chia sẻ source code Orange Rain in Winform
- [DEVEXPRESS] Hướng dẫn sử dụng HTML Template trên XtraMessageBox Winform Devexpress 22.2.3
- [DEVEXPRESS] Hướng dẫn sử dụng HTML and CSS Code Viewer trên Winform
- [C#] Number Effect Counter up and down in winform
- [C#] Hướng dẫn Supend and Resume Process ID in Winform
- [C#] Hiển thị line number trên Richtextbox Winform
- [C#] Fake Blue Screen BSOD in winform
- [C#] Chia sẽ code demo sử dụng Async Parallel Foreach and For in Winform
- [C#] Sử dụng ActionBlock run X task at time winform
- [C#] Hướng dẫn sử dụng Property Grid để lưu và tải lại thông tin cấu hình user trên winform
[C#] Chia sẽ class INIHelper dùng để ghi và đọc file config INI
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#:
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:
Thanks for watching!