INI File Reading and Writing in C#: Native Absence and Third-Party Solutions

Nov 09, 2025 · Programming · 12 views · 7.8

Keywords: C# | .NET | INI Files | P/Invoke | Configuration Files

Abstract: This article provides an in-depth analysis of INI file handling in the .NET framework, examining Microsoft's preference for XML-based configuration files and detailing implementation methods through P/Invoke calls to Windows API. The paper compares multiple implementation approaches, including custom classes and third-party NuGet packages, offering developers a comprehensive guide to INI file processing. Through practical code examples and performance analysis, it helps readers choose the most suitable INI handling solution for different scenarios.

The State of INI Files in .NET Ecosystem

Within the C# and .NET development environment, INI files as a traditional configuration format exhibit significant differences in official support compared to languages like Delphi. Microsoft's framework design strongly favors XML-based configuration files, resulting in no built-in INI file handling classes within the .NET framework itself. This design choice reflects Microsoft's recommendations for modern configuration management best practices, while simultaneously presenting challenges for developers working with legacy systems or specific scenarios.

P/Invoke Implementation Using Windows API

Although the .NET framework lacks native INI support, Platform Invocation Services (P/Invoke) enable access to Windows operating system's INI file handling capabilities. The core implementation relies on two crucial functions from kernel32.dll:

using System.Runtime.InteropServices;
using System.Text;

[DllImport("kernel32", CharSet = CharSet.Unicode)]
static extern long WritePrivateProfileString(string section, string key, string value, string filePath);

[DllImport("kernel32", CharSet = CharSet.Unicode)]
static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);

These functions provide basic read-write capabilities but require developers to encapsulate them into more user-friendly classes. A complete implementation should include constructor methods for file path management, along with method encapsulation for basic operations like reading, writing, and deletion.

Complete Implementation of Custom INI Handling Class

Building upon Windows API, developers can construct a fully-featured INI file handling class. This class needs to properly handle critical aspects such as file path resolution, default value settings, and error handling:

public class IniFile
{
    private string filePath;
    
    public IniFile(string iniPath = null)
    {
        // Path handling logic: supports both relative and absolute paths
        if (string.IsNullOrEmpty(iniPath))
        {
            var assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            iniPath = assemblyName + ".ini";
        }
        filePath = System.IO.Path.GetFullPath(iniPath);
    }
    
    public string Read(string key, string section = null)
    {
        var buffer = new StringBuilder(256);
        GetPrivateProfileString(section ?? "DefaultSection", key, string.Empty, buffer, buffer.Capacity, filePath);
        return buffer.ToString();
    }
    
    public void Write(string key, string value, string section = null)
    {
        WritePrivateProfileString(section ?? "DefaultSection", key, value, filePath);
    }
}

Third-Party Solutions and NuGet Packages

Beyond custom implementations, developers can opt for mature third-party solutions. The NuGet repository offers multiple INI processing libraries, such as INI Parser. These libraries typically provide richer feature sets, including:

The advantage of choosing third-party libraries lies in reduced development effort while gaining more stable functionality and better community support.

Practical Application Scenarios and Best Practices

INI files maintain practical value in embedded systems and traditional desktop applications. Reference articles mention application cases in cRIO systems, demonstrating INI file advantages in resource-constrained environments. Development considerations should include:

Performance Considerations and Alternative Solutions

While INI file processing is relatively lightweight, alternative solutions should be considered in high-performance scenarios. JSON, XML, or binary formats may offer better performance characteristics. Configuration format selection should comprehensively evaluate factors like file size, parsing speed, readability, and toolchain support.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.