All Projects → cemdervis → Sharpconfig

cemdervis / Sharpconfig

Licence: mit
An easy to use CFG/INI configuration library for .NET.

Projects that are alternatives of or similar to Sharpconfig

Vncorenlp
A Vietnamese natural language processing toolkit (NAACL 2018)
Stars: ✭ 354 (-19.91%)
Mutual labels:  parsing
Sbjson
This framework implements a strict JSON parser and generator in Objective-C.
Stars: ✭ 3,776 (+754.3%)
Mutual labels:  parsing
Macho Kit
A C/Objective-C library for parsing Mach-O files.
Stars: ✭ 416 (-5.88%)
Mutual labels:  parsing
See Phit
A C++ HTML template engine that uses compile time HTML parsing
Stars: ✭ 370 (-16.29%)
Mutual labels:  parsing
Jflex
The fast scanner generator for Java™ with full Unicode support
Stars: ✭ 380 (-14.03%)
Mutual labels:  parsing
Binjs Ref
Reference implementation for the JavaScript Binary AST format
Stars: ✭ 399 (-9.73%)
Mutual labels:  parsing
Como Lang Ng
como-lang-ng is now ana-lang, located at https://github.com/analang/ana
Stars: ✭ 342 (-22.62%)
Mutual labels:  parsing
Cpp Peglib
A single file C++ header-only PEG (Parsing Expression Grammars) library
Stars: ✭ 435 (-1.58%)
Mutual labels:  parsing
Json.h
🗄️ single header json parser for C and C++
Stars: ✭ 387 (-12.44%)
Mutual labels:  parsing
Toou 2d
基于Qt Quick(Qml) 跨平台技术打造的2D框架
Stars: ✭ 413 (-6.56%)
Mutual labels:  ini
Nlpnet
A neural network architecture for NLP tasks, using cython for fast performance. Currently, it can perform POS tagging, SRL and dependency parsing.
Stars: ✭ 379 (-14.25%)
Mutual labels:  parsing
Pspnet Keras Tensorflow
TensorFlow implementation of original paper : https://github.com/hszhao/PSPNet
Stars: ✭ 381 (-13.8%)
Mutual labels:  parsing
Jsoniter Scala
Scala macros for compile-time generation of safe and ultra-fast JSON codecs
Stars: ✭ 410 (-7.24%)
Mutual labels:  parsing
Scnlib
scanf for modern C++
Stars: ✭ 359 (-18.78%)
Mutual labels:  parsing
Seafox
A blazing fast 100% spec compliant, self-hosted javascript parser written in Typescript
Stars: ✭ 425 (-3.85%)
Mutual labels:  parsing
Reek
Code smell detector for Ruby
Stars: ✭ 3,693 (+735.52%)
Mutual labels:  parsing
Csv
CSV Decoding and Encoding for Elixir
Stars: ✭ 398 (-9.95%)
Mutual labels:  parsing
Angstrom
Parser combinators built for speed and memory efficiency
Stars: ✭ 434 (-1.81%)
Mutual labels:  parsing
Phonenumberkit
A Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.
Stars: ✭ 4,362 (+886.88%)
Mutual labels:  parsing
Emacs Tree Sitter
Tree-sitter for Emacs
Stars: ✭ 409 (-7.47%)
Mutual labels:  parsing

sharpconfig_logo.png

NuGet version Build status

SharpConfig is an easy to use CFG/INI configuration library for .NET.

You can use SharpConfig to read, modify and save configuration files and streams, in either text or binary format.

The library is fully compatible with .NET, .NET Core and the Mono Framework.

An example Configuration

[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<DayOfWeek>();

// Entire user-defined objects can be created from sections and vice versa.
var person = config["Person"].ToObject<Person>();
// ...

Iterating through a Configuration

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;
// ...

Loading a Configuration

Configuration.LoadFromFile("myConfig.cfg");        // Load from a text-based file.
Configuration.LoadFromStream(myStream);            // Load from a text-based stream.
Configuration.LoadFromString(myString);            // Load from text (source code).
Configuration.LoadFromBinaryFile("myConfig.cfg");  // Load from a binary file.
Configuration.LoadFromBinaryStream(myStream);      // Load from a binary stream.

Saving a Configuration

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 the current ones:

  • CultureInfo Configuration.CultureInfo { get; set; }

    • Gets or sets the CultureInfo that is used for value conversion in SharpConfig. The default value is CultureInfo.InvariantCulture.
  • char[] Configuration.ValidCommentChars { get; }

    • Gets the array that contains all valid comment delimiting characters. The current value is { '#', ';' }.
  • char Configuration.PreferredCommentChar { get; set; }

    • Gets or sets the preferred comment char when saving configurations. The default value is '#'.
  • char Configuration.ArrayElementSeparator { get; set; }

    • Gets or sets the array element separator character for settings. The default value is ','.
    • Remember that after you change this value while Setting instances exist, to expect their ArraySize and other array-related values to return different values.
  • bool Configuration.IgnoreInlineComments { get; set; }

    • Gets or sets a value indicating whether inline-comments should be ignored when parsing a configuration.
  • bool Configuration.IgnorePreComments { get; set; }

    • Gets or sets a value indicating whether pre-comments should be ignored when parsing a configuration.
  • bool Configuration.SpaceBetweenEquals { get; set; }

    • Gets or sets a value indicating whether space between equals should be added when creating a configuration.
  • bool Configuration.OutputRawStringValues { get; set; }

    • Gets or sets a value indicating whether string values are written without quotes, but including everything in between. Example:
      • The setting MySetting=" Example value" is written to a file in as MySetting= Example value

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 of type SomeClass and vice versa. Now suppose you have a type in your project that should always be ignored. You would have to mark every property that returns this type with a [SharpConfig.Ignore] attribute. An easier solution is to just apply the [SharpConfig.Ignore] attribute to the type.

Example:

[SharpConfig.Ignore]
class ThisTypeShouldAlwaysBeIgnored
{
    // ...
}

instead of:

[SharpConfig.Ignore]
class SomeClass
{
    [SharpConfig.Ignore]
    public ThisTypeShouldAlwaysBeIngored T1 { get; set; }

    [SharpConfig.Ignore]
    public ThisTypeShouldAlwaysBeIngored T2 { get; set; }

    [SharpConfig.Ignore]
    public ThisTypeShouldAlwaysBeIngored T3 { get; set; }
}

This ignoring mechanism works the same way for public fields.

Adding custom object converters

There may be cases where you want to implement conversion rules for a custom type, with specific requirements. This is easy and involves two steps, which are illustrated using the Person example:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Step 1: Create a custom converter class that derives from SharpConfig.TypeStringConverter<T>:

using SharpConfig;
public class PersonStringConverter : TypeStringConverter<Person>
{
    // This method is responsible for converting a Person object to a string.
    public override string ConvertToString(object value)
    {
        var person = (Person)value;
        return string.Format("[{0};{1}]", person.Name, person.Age);
    }

    // This method is responsible for converting a string to a Person object.
    public override object ConvertFromString(string value, Type hint)
    {
        var split = value.Trim('[', ']').Split(';');

        var person = new Person();
        person.Name = split[0];
        person.Age = int.Parse(split[1]);

        return person;
     }
}

Step 2: Register the PersonStringConverter (anywhere you like):

using SharpConfig;
Configuration.RegisterTypeStringConverter(new PersonStringConverter());

That's it!

Whenever a Person object is used on a Setting (via GetValue() and SetValue()), your converter is selected to take care of the conversion. This also automatically works with SetValue() for arrays and GetValueArray().

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].