To read and write INI or configuration-like files manually in C# (without using third-party libraries), you can create a simple parser using
StreamReader, StreamWriter, and Dictionary<string, Dictionary<string, string>> to represent sections and key-value pairs.
using System;
using System.Collections.Generic;
using System.IO;
public class IniFile
{
public Dictionary<string, Dictionary<string, string>> Data { get; } = new();
public void Load(string filePath)
{
string? section = null;
foreach (var line in File.ReadLines(filePath))
{
var trimmed = line.Trim();
if (string.IsNullOrWhiteSpace(trimmed) || trimmed.StartsWith(";") || trimmed.StartsWith("#"))
continue;
if (trimmed.StartsWith("[") && trimmed.EndsWith("]"))
{
section = trimmed[1..^1].Trim();
if (!Data.ContainsKey(section))
Data[section] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
else if (section != null && trimmed.Contains('='))
{
var parts = trimmed.Split('=', 2);
var key = parts[0].Trim();
var value = parts[1].Trim();
Data[section][key] = value;
}
}
}
public string? Get(string section, string key)
{
if (Data.TryGetValue(section, out var kv) && kv.TryGetValue(key, out var value))
return value;
return null;
}
}
Usage:
var ini = new IniFile();
ini.Load("config.ini");
string? server = ini.Get("Database", "Server");
Console.WriteLine(server); // Outputs: localhost
2. Writing INI Files Manually
public void Save(string filePath)
{
using var writer = new StreamWriter(filePath);
foreach (var section in Data)
{
writer.WriteLine($"[{section.Key}]");
foreach (var kvp in section.Value)
{
writer.WriteLine($"{kvp.Key}={kvp.Value}");
}
writer.WriteLine(); // Blank line between sections
}
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To read and write INI or configuration-like files manually in C# (without using third-party libraries), you can create a simple parser using
StreamReader,StreamWriter, andDictionary<string, Dictionary<string, string>>to represent sections and key-value pairs.INI Format Example
1. Reading INI Files Manually
Usage:
2. Writing INI Files Manually
Usage:
Notes and Best Practices
;or#)Let me know if you want extended support for features like multi-line values or type conversion (int, bool, etc.).