SharpConfig is a simple, powerful, and lightweight .NET configuration library. You can use it to read, modify and save configuration files and streams, in either text or binary format.
Installation
Choose one of the following methods to install SharpConfig:
- .NET CLI:
dotnet add package sharpconfig - NuGet Package Manager:
Install-Package sharpconfig - Source: Latest Source Code (.zip)
Examples
An example configuration file (sample.cfg):
[General]
# a comment
SomeString = Hello World!
SomeInteger = 10 # an inline comment
SomeFloat = 20.05
SomeBoolean = true
SomeArray = { 1, 2, 3 }
Day = Monday
[Person]
Name = Peter
Age = 50
To read these values, your C# code would look like:
var config = Configuration.LoadFromFile("sample.cfg");
var section = config["General"];
string someString = section["SomeString"].StringValue;
int someInteger = section["SomeInteger"].IntValue;
float someFloat = section["SomeFloat"].FloatValue;
bool someBool = section["SomeBoolean"].BoolValue;
int[] someIntArray = section["SomeArray"].IntValueArray;
string[] someStringArray = section["SomeArray"].StringValueArray;
DayOfWeek day = section["Day"].GetValue();
// Entire user-defined objects can be created from sections and vice versa.
var person = config["Person"].ToObject();
Loading
var cfg1 = Configuration.LoadFromFile("myConfig.cfg"); // Load from a text-based file.
var cfg2 = Configuration.LoadFromStream(myStream); // Load from a text-based stream.
var cfg3 = Configuration.LoadFromString(myString); // Load from text (source code).
var cfg4 = Configuration.LoadFromBinaryFile("myConfig.cfg"); // Load from a binary file.
var cfg5 = Configuration.LoadFromBinaryStream(myStream); // Load from a binary stream.
Iterating
// A configuration conforms to IEnumerable and therefore supports normal iteration.
foreach (var section in myConfig)
{
foreach (var setting in section)
{
// ...
}
}
Creating a configuration in memory
// Create the configuration.
var myConfig = new Configuration();
// Set some values.
// This will automatically create the sections and settings.
myConfig["Video"]["Width"].IntValue = 1920;
myConfig["Video"]["Height"].IntValue = 1080;
// Set an array value.
myConfig["Video"]["Formats"].StringValueArray = new[] { "RGB32", "RGBA32" };
// Get the values just to test.
int width = myConfig["Video"]["Width"].IntValue;
int height = myConfig["Video"]["Height"].IntValue;
string[] formats = myConfig["Video"]["Formats"].StringValueArray;
Saving
myConfig.SaveToFile("myConfig.cfg"); // Save to a text-based file.
myConfig.SaveToStream(myStream); // Save to a text-based stream.
myConfig.SaveToBinaryFile("myConfig.cfg"); // Save to a binary file.
myConfig.SaveToBinaryStream(myStream); // Save to a binary stream.
Options
Sometimes a project has special configuration files or other needs, for example ignoring all comments in a file.
To allow for greater flexibility, SharpConfig's behavior is modifiable using static properties of the Configuration class.
The following properties are available:
| Option | Type | Description |
|---|---|---|
CultureInfo |
CultureInfo |
Gets or sets the CultureInfo that is used for value conversion. Default is InvariantCulture. |
ValidCommentChars |
char[] |
Valid comment delimiting characters. Default: { '#', ';' } |
PreferredCommentChar |
char |
Preferred comment char when saving. Default: '#'. |
ArrayElementSeparator |
char |
Separator for settings. Default: ','. |
IgnoreInlineComments |
bool |
Whether inline comments should be ignored when parsing. |
IgnorePreComments |
bool |
Whether pre-comments should be ignored when parsing. |
SpaceBetweenEquals |
bool |
Whether space between equals should be added when saving. |
OutputRawStringLiterals |
bool |
Whether string values are written without quotes. |
Ignoring properties, fields and types
Suppose you have the following class:
class SomeClass
{
public string Name { get; set; }
public int Age { get; set; }
[SharpConfig.Ignore]
public int SomeInt { get; set; }
}
SharpConfig will now ignore the SomeInt property when creating sections from objects and vice versa.
An easier solution for types is to apply the [SharpConfig.Ignore] attribute to the type itself:
[SharpConfig.Ignore]
class ThisTypeShouldAlwaysBeIgnored
{
// ...
}
Note: This ignoring mechanism works the same way for public fields.
Adding custom object converters
You can implement conversion rules for custom types by deriving from SharpConfig.TypeStringConverter<T>.
Step 1: Create a custom converter
public class PersonStringConverter : TypeStringConverter<Person>
{
public override string ConvertToString(object value)
{
var person = (Person)value;
return string.Format("[{0};{1}]", person.Name, person.Age);
}
public override object ConvertFromString(string value, Type hint)
{
var split = value.Trim('[', ']').Split(';');
return new Person { Name = split[0], Age = int.Parse(split[1]) };
}
}
Step 2: Register the converter
Configuration.RegisterTypeStringConverter(new PersonStringConverter());
That's it! Your converter is now selected whenever a Person object is used on a Setting.