3 Pluspunkte 0 Minuspunkte
Wie kann ich INI Dateien in C# parsen?
von  

1 Antwort

0 Pluspunkte 0 Minuspunkte

Eine Möglichkeit besteht darin den System.IO Namespace zu verwenden, um die Datei Zeile für Zeile zu lesen und die relevanten Informationen zu extrahieren.

using System;
using System.Collections.Generic;
using System.IO;

class IniFileParser
{
    private readonly Dictionary<string, Dictionary<string, string>> sections;

    public IniFileParser()
    {
        sections = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
    }

    public void Parse(string filePath)
    {
        string currentSection = null;
        foreach (string line in File.ReadLines(filePath))
        {
            string trimmedLine = line.Trim();

            if (string.IsNullOrWhiteSpace(trimmedLine) || trimmedLine.StartsWith(";") || trimmedLine.StartsWith("#"))
            {
                // Skip comments and empty lines
                continue;
            }

            if (trimmedLine.StartsWith("[") && trimmedLine.EndsWith("]"))
            {
                // Found a new section
                currentSection = trimmedLine.Substring(1, trimmedLine.Length - 2);
                sections[currentSection] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            }
            else
            {
                // Found key-value pair
                int equalsIndex = trimmedLine.IndexOf('=');
                if (equalsIndex >= 0)
                {
                    string key = trimmedLine.Substring(0, equalsIndex).Trim();
                    string value = trimmedLine.Substring(equalsIndex + 1).Trim();
                    sections[currentSection][key] = value;
                }
            }
        }
    }

    public string GetValue(string section, string key)
    {
        if (sections.ContainsKey(section) && sections[section].ContainsKey(key))
        {
            return sections[section][key];
        }
        return null;
    }
}

class Program
{
    static void Main()
    {
        IniFileParser iniParser = new IniFileParser();
        iniParser.Parse("example.ini");

        // Beispiel: Wert aus der Sektion "Section1" und dem Schlüssel "Key1" abrufen
        string value = iniParser.GetValue("Section1", "Key1");
        Console.WriteLine($"Value: {value}");
    }
}
von (706 Punkte)