SharpConfig: A Beginner’s Guide to Getting StartedSharpConfig is a lightweight, easy-to-use configuration library for .NET applications. It provides a simple file format and a small API that lets you read, write, and manage application settings without the complexity of larger configuration systems. This guide will walk you through the fundamentals: installation, file format, core API concepts, common usage patterns, error handling, and tips for organizing configuration in real projects.
What is SharpConfig?
SharpConfig is a .NET configuration library that uses a human-readable text format inspired by INI files but with richer structure (sections, settings, arrays, and nested sections). It’s designed primarily for desktop and small server applications where you want a fast, minimal dependency configuration solution.
Why choose SharpConfig?
- Simple and readable file format: configuration files are easy for humans to edit.
- Lightweight: minimal API surface and low runtime overhead.
- Flexible typing: supports strings, integers, floats, booleans, enums, arrays, and nested sections.
- Round-trip safe: reads and writes without losing comments or original ordering in many implementations (depending on version).
- Works with .NET Standard/Core and .NET Framework: broad compatibility.
Installing SharpConfig
To add SharpConfig to your project, use NuGet. From the command line in your project directory:
dotnet add package SharpConfig
Or install via the Visual Studio NuGet Package Manager by searching for “SharpConfig”.
Configuration file format
SharpConfig files are similar to INI but allow more structure.
Example config file (example.cfg):
# Application configuration [Application] Name = MyApp Version = 1.2.3 Debug = true [Database] Host = localhost Port = 5432 User = dbuser Password = secret [UI] Theme = dark RecentFiles = [ "doc1.txt", "doc2.txt", "notes.md" ] [Logging] Level = Info Outputs = [ "console", "file" ]
Key points:
- Sections are declared with [SectionName].
- Settings are key = value pairs.
- Arrays use square brackets and comma-separated values.
- Comments start with #.
Core API concepts
SharpConfig exposes three main concepts:
- Configuration: the top-level container representing the whole file.
- Section: a named collection of settings (and optionally nested sections).
- Setting: a typed key/value pair.
Common classes and methods:
- Configuration.LoadFromFile(path) / Configuration.LoadFromStream(…)
- config.SaveToFile(path)
- config[“Section”][“Key”] to get a Setting object
- Setting.GetValue
() / Setting.SetValue(…) to read or write values - Section.Add() / Section.Remove() to modify structure
Basic usage examples
Below are typical usage patterns in C#.
Reading a config file:
using SharpConfig; var config = Configuration.LoadFromFile("example.cfg"); var appName = config["Application"]["Name"].GetValue<string>(); var version = config["Application"]["Version"].GetValue<string>(); var debug = config["Application"]["Debug"].GetValue<bool>();
Writing or modifying values:
using SharpConfig; var config = Configuration.LoadFromFile("example.cfg"); config["Application"]["Name"].SetValue("MyUpdatedApp"); config["Application"]["MaxUsers"] = new Setting("MaxUsers", 100); // add a setting config.SaveToFile("example_updated.cfg");
Working with arrays:
var recent = config["UI"]["RecentFiles"].Values; // returns array/string list foreach (var item in recent) Console.WriteLine(item);
Creating a new configuration programmatically:
var config = new Configuration(); var section = new Section("Application"); section.Add(new Setting("Name", "NewApp")); section.Add(new Setting("Version", "0.1")); config.Add(section); config.SaveToFile("new.cfg");
Handling missing sections or settings
Always check for nulls to avoid exceptions:
var appSection = config["Application"]; if (appSection != null) { var nameSetting = appSection["Name"]; if (nameSetting != null) Console.WriteLine(nameSetting.GetValue<string>()); }
Or use safe helpers and defaults:
string name = config["Application"]?["Name"]?.GetValue<string>() ?? "DefaultApp";
Data types and parsing
SharpConfig supports common primitive types and enums. Use GetValue
enum LogLevel { Debug, Info, Warn, Error } var level = config["Logging"]["Level"].GetValue<LogLevel>();
For custom parsing, read as string and parse manually.
Best practices for organizing configuration
- Group related settings into sections (Database, Logging, UI).
- Keep secrets out of plaintext config files; use environment variables or a secrets manager for production.
- Use defaults in code so missing settings don’t break startup.
- Keep config files under version control for non-sensitive settings; ignore ones with secrets.
Error handling and validation
- Validate required settings at startup and fail fast with clear error messages.
- Use try/catch when loading/parsing if file may be malformed.
- Provide clear fallback values when appropriate.
Example validation:
if (!int.TryParse(config["Database"]?["Port"]?.Value, out var port)) throw new ConfigurationErrorsException("Database port is invalid or missing.");
Advanced tips
- Use nested sections for grouped settings (if supported by your SharpConfig version).
- Use arrays for list-like settings (recent files, enabled features).
- When modifying and writing config, preserve comments where possible — test save/load behavior for your library version.
- Consider wrapping SharpConfig access behind a typed configuration wrapper class in your app to centralize parsing and defaults.
Common pitfalls
- Treating configuration files as secure storage for credentials.
- Assuming every environment has the same file path — support environment-specific config or environment variables.
- Relying on implicit parsing — explicitly validate numeric and boolean conversions.
Example: small real-world app
Brief sketch for a console app that uses SharpConfig:
- Load config (if missing, create a default file).
- Validate required settings (DB connection info).
- Connect to services using config values.
- If the user runs a –set option, update config and save.
This pattern keeps runtime behavior predictable and config-driven.
Alternatives and when not to use SharpConfig
If you need hierarchical, complex configuration bound directly to typed objects (with dependency injection) in ASP.NET Core, prefer Microsoft.Extensions.Configuration. For encrypted secrets and enterprise secret rotation, use a secrets manager. Use SharpConfig when you need a small, human-editable config format for desktop or small services.
Summary
SharpConfig is a practical, minimal library for straightforward configuration needs in .NET projects. It shines when you want a readable, editable file format and a tiny API surface. Use it for desktop apps, small services, or tooling where simplicity and readability matter more than enterprise features like secret management, cloud binding, or DI integration.
Leave a Reply