SharpConfig: A Beginner’s Guide to Getting Started

SharpConfig: A Beginner’s Guide to Getting StartedSharpConfig is a lightweight, flexible configuration library for .NET that provides a human-readable, editable format for storing application settings. If you’re building a .NET application and want a simple alternative to JSON, XML, or Windows registry settings that combines readability with typed access, SharpConfig is a strong candidate. This guide will walk you through what SharpConfig is, when to use it, installation, core concepts, common tasks, tips, and some best practices.


What is SharpConfig?

SharpConfig is an open-source configuration library for .NET applications that stores settings in an INI-like format with additional structure and typed values. It supports sections, settings, arrays, nested values, comments, and basic parsing for primitive types. The library aims to be simple to use while offering more structure and type-safety than the classic INI approach.

Key short fact: SharpConfig uses an INI-like, human-editable format and exposes strongly typed access to settings.


When to use SharpConfig

  • When you need a small, dependency-light configuration system.
  • When human readability and editability of configuration files is important.
  • When you prefer a file-based configuration that can be manually edited without tools.
  • For desktop apps, small services, game settings, tools, and utilities where a full settings server or complex format is unnecessary.

Avoid SharpConfig if you require advanced schema validation, hierarchical JSON-like documents with complex nested arrays/objects, or if you need features like remote configuration management and versioning out of the box.


Installing SharpConfig

To add SharpConfig to a .NET project, use NuGet. From the command line in your project folder:

dotnet add package SharpConfig 

Or install via the NuGet Package Manager in Visual Studio by searching for “SharpConfig”.


Core concepts

  • Section: A named grouping similar to INI sections. Sections contain multiple settings.
  • Setting: A named value inside a section. Settings are typed (string, int, bool, float, DateTime, enums, arrays).
  • Configuration: The top-level container that holds sections.
  • Comments: Lines in the file prefixed with # or ; (depending on formatting) that are preserved and can be attached to sections or settings.

File format example:

[General] AppName = MyApp Version = 1.0 [Window] Width = 1024 Height = 768 Fullscreen = false 

Basic usage examples

Below are typical tasks you’ll perform with SharpConfig, with concise code examples.

  1. Create a new configuration and save to disk
using SharpConfig; var config = new Configuration(); var section = new Section("General"); section.Add("AppName", "MyApp"); section.Add("Version", 1.0); config.Add(section); config.SaveToFile("config.cfg"); 
  1. Load configuration from file and read values
using SharpConfig; var config = Configuration.LoadFromFile("config.cfg"); string appName = config["General"]["AppName"].Value; double version = config["General"]["Version"].AsDouble(); int width = config["Window"]["Width"].AsInt(); bool fullscreen = config["Window"]["Fullscreen"].AsBool(); 
  1. Update a value and save
config["Window"]["Width"].Value = "1280"; config.SaveToFile("config.cfg"); 
  1. Working with arrays

File snippet:

[Audio] Volumes = {0.5, 0.7, 1.0} 

Reading:

var volumes = config["Audio"]["Volumes"].AsFloatArray(); 
  1. Enums and DateTimes
// Enum public enum LogLevel { Debug, Info, Warn, Error } config["Logging"].Add("Level", LogLevel.Info); var level = (LogLevel)config["Logging"]["Level"].AsEnum(typeof(LogLevel)); // DateTime config["General"].Add("LastRun", DateTime.UtcNow); var lastRun = config["General"]["LastRun"].AsDateTime(); 

Parsing and type safety

SharpConfig stores values as text but provides typed accessors (AsInt, AsBool, AsDateTime, AsEnum, AsFloatArray, etc.). Use these to avoid manual parsing and to fail early if a value cannot be converted.

Handle potential parsing errors by checking for nulls or wrapping access in try/catch if you expect malformed user edits.


Comments and formatting

SharpConfig preserves comments and formatting when loading and saving. You can add comments programmatically:

var s = new Section("General"); s.Comment = "Main application settings"; s["AppName"].Comment = "User visible application name"; 

When saved, comments are emitted above the sections/settings they belong to.


Advanced tips

  • Use defaults: Load config, check for existence of sections/settings and populate defaults programmatically before saving. That lets you ship a clean default file and preserve user changes.
  • Validation: Implement validation logic after loading (range checks, required settings). Throw or reset to defaults when values are invalid.
  • Encryption: SharpConfig doesn’t provide encryption. For sensitive values (API keys, passwords) store encrypted blobs or use OS-protected secure stores (Windows DPAPI, macOS Keychain).
  • Thread-safety: Configuration object methods are not guaranteed to be thread-safe. Synchronize access if you read/write concurrently.
  • Migrations: If you change keys or structure between versions, implement a migration step on load that transforms old keys into the new format.

Pros and cons

Pros Cons
Human-readable and editable Not a full schema/validation engine
Lightweight and simple API Limited advanced data structures compared to JSON
Typed accessors for convenience No built-in encryption or remote management
Preserves comments and formatting Not guaranteed thread-safe

Example: Bootstrapping config with defaults and migration

var configFile = "config.cfg"; Configuration config; if (File.Exists(configFile)) {     config = Configuration.LoadFromFile(configFile);     // Migration example: rename "Window/Fullscreen" to "Window/IsFullscreen"     var w = config["Window"];     if (w != null && w["Fullscreen"] != null && w["IsFullscreen"] == null)     {         w.Add("IsFullscreen", w["Fullscreen"].Value);         w.Remove("Fullscreen");     } } else {     config = new Configuration();     var general = new Section("General");     general.Add("AppName", "MyApp");     general.Add("Version", 1.0);     config.Add(general);     var window = new Section("Window");     window.Add("Width", 1024);     window.Add("Height", 768);     window.Add("IsFullscreen", false);     config.Add(window);     config.SaveToFile(configFile); } 

Common pitfalls

  • Relying on AsXxx methods without checking input—user-edited files can be malformed.
  • Expecting complex nested JSON-style structures—SharpConfig is closer to INI semantics.
  • Storing secrets in plain text—use encrypted storage for sensitive data.
  • Assuming thread-safety—use locks around shared config objects.

Alternatives

  • JSON.NET / System.Text.Json with appsettings.json — better for complex hierarchical data, broad ecosystem support.
  • YAML (YamlDotNet) — human-friendly, supports complex structures, but heavier.
  • Microsoft.Extensions.Configuration — flexible, supports multiple providers (JSON, env vars, command line), recommended for ASP.NET Core apps.

Conclusion

SharpConfig is a practical, human-friendly configuration library for .NET apps that need readable INI-like files with typed access and comment preservation. It’s best for desktop applications, small tools, and scenarios where simplicity and manual editability matter more than advanced schema validation or cloud-based configuration. Start by installing the package, define sensible defaults, validate user input on load, and migrate old configs when your app evolves.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *