Advanced example

This tutorial explains advanced functionality, such as setting transfer, category managing, and LINQ enumerating.


Go back

Delete settings

When I delete you maybe I'll stop feeling so bad

Individual settings can be deleted using the .DeleteKey() method, passing the key of a setting. If the setting doesn't exist, this call will do nothing.

var config; // Assume initialized

// Delete a global setting
config.DeleteKey("Timespan");

// Delete a categorized setting
config.DeleteKey("User1:Token");

You can also delete entire categories in a single call, using the .DeleteSection() method. In this case, pass the name of a category as a parameter:

var config; // Assume initialized

config.Write("User:Name", "Foo");
config.Write("User:Age", 18);
config.Write("ServerPort", 80);

// Delete the User category
config.DeleteSection("User");

// Both User:Name and User:Age are deleted
// ServerPort isn't part of the User category, so it remains unaffected

Transfer settings

Settings can be transferred from one file to another.

This process generates a copy of all settings in the source file, leaving it untouched. This is useful to create backups, for example.

To do so, use the .TransferTo() method, passing another config instance:

var config = XmlConfig.From("source.xml");

// Transfer to another XML file
config.TransferTo(XmlConfig.From("target.xml"));

// Transfer to a different file format
config.TransferTo(IniConfig.From("target.ini"));

Note that you can even transfer between different file formats while keeping all data, including comments.

Accio LINQ!

Time to cast some magic.

There are two main ways to obtain enumerables from a settings file:

Call .SettingsIn() to receive an instance of IDictionary<string, string> with all settings inside the specified section.

Or call .AsTransferable().ReadAll() to receive an instance of IEnumerable<Setting> with all settings in the file.

var config; // Assume initialized

// Operate on the settings of a category
var settings = config.SettingsIn("User");
var result = settings.Where(kvp => kvp.Key.Length > 2)
                        .Select(kvp => kvp.Value);
                        
// Operate on all settings in the file
var settings = config.AsTransferable().ReadAll();
var result = settings.Where(s => s.Key is "Age")
                        .OrderBy(n => n)
                        .Select(s => int.Parse(s.Value))
                        .Distinct();

You're all done!

Now you know how to get the most value out of ConfigAdapter.


Go back