Question

I can use the .Net ConfigurationManager to store strings, but how can I store structured data?

For example, I can do this:

conf = ConfigurationManager.OpenExeConfiguration(...)
string s = "myval";
conf.AppSettings.Settings["mykey"].Value = s;
conf.Save(ConfigurationSaveMode.Modified);

And I would like to do this:

class myclass {
   public string s;
   int i;
   ... more elements
};

myclass c = new myclass(); c.s = "mystring"; c.i = 1234; ...

conf.AppSettings.Settings["mykey"] = cc;
conf.Save(ConfigurationSaveMode.Modified);

How do I store and retrieve structured data with the ConfigurationManager?

I implemented a solution as @sll suggested. But then difficulty was to create a new section to the configuration. Here is how this is done: How to Write to a User.Config file through ConfigurationManager?

Was it helpful?

Solution

You can create own configuration section type by inheriting from ConfigurationSection class and use it to save/load any custom type information.

MSDN: How to: Create Custom Configuration Sections Using ConfigurationSection

BTW, One advice which might be helpful for you or others: One good thing is making custom configurations section class immutable (no public setters) so you can be sure that configuration cannot be changed on any stage of application life cycle, but then if you decide writing unit tests for code which relies on configuration section class and need section stub with some test values you might stuck with abilty to set property values since there is no setters. Solution is providing a new class which is inherited from your section class and specifying in constructor values using protected indexer like show below:

public class TestSectionClass: MyConfigurationSection
{
    public TestSectionClass(string testUserName)
    {
        this["userName"] = testUserName;
    }
}

OTHER TIPS

Serialization.

There are numerous different ways of serializing data, so you'd need to pick one. But .NET provides a serialization API that suits a great many cases, and in working with web AJAX calls recently I find myself using JavaScriptSerializer heavily to turn things into JSON. However there are third party libraries such as protobuf-net, and so on.

The key here is to essentially turn your data into a byte or string representation that can later be deserialized back to its original structure at a later date, allowing you to store it in a medium between then, such as in configuration files or transmission over networks etc.

As per @sll's answer, .NET has another facet meaning it can handle serialization of data in and out of custom configuration sections; whether you want to begin specifying types explicitly for this purpose or not is your call. Bottom line is the same, serialize, somehow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top