How to export and import properity settings of a tool.

c#chris

Member
Joined
Dec 10, 2024
Messages
13
Programming Experience
1-3
Hello,

I want to implement a function in c#, that writes the settings of all public properties of all classes into a json file, so that the file can also be imported at other locations for restoring the properties.

Do you have some hints how to start here ?

Best regards
 
Read about "serialization"
 
Export Public Properties to JSON:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;

public class PropertyExporter
{
    public static void ExportPropertiesToJson(string filePath)
    {
        var allPublicProperties = Assembly.GetExecutingAssembly()
            .GetTypes()
            .SelectMany(t => t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            .ToList();

        var propertiesDictionary = new Dictionary<string, object>();

        foreach (var property in allPublicProperties)
        {
            propertiesDictionary[property.DeclaringType.Name + "." + property.Name] = property.GetValue(Activator.CreateInstance(property.DeclaringType));
        }

        var json = JsonConvert.SerializeObject(propertiesDictionary, Formatting.Indented);
        File.WriteAllText(filePath, json);
    }
}
 
How will that work for any existing objects that have already been instantiated? How will that work for objects which have constructors that require parameters?
 
Is my understanding correct, that with the following statements all properties of my class and subclasses are automatically written to a file in json format ?

C#:
var _setingsFile = _settingsFileLocation + "test.json";
string sentinelJSON =  JsonConvert.SerializeObject(this, Formatting.Indented);

using (StreamWriter writer = new StreamWriter(_setingsFile, true))
{
    writer.WriteLine(sentinelJSON);
}


Reading it back should also not be a big problem, but how do I "map" it back to the properties ?
 
Yes it will write out all your public properties and fields into a JSON file. When you use the DeserializeObject, it will create a new instance of your class with all the values set. There is no need for you ta map it back into the public fields and properties. That's what the deserializer does for you.
 
According to my understanding for deserialization I would need to say:
this = JsonConvert.DeserializeObject(sentinelJSON);
But "this" is read only.
Since I am working on an plugin dll, which uses my class, I do not know the instance name of my class.
So what I should enter here ?
 
What you do is have a static method that instantiates your settings class. Something like this pseudo code:
C#:
class MyCoolAppSettings
{
    public string CharacterName { get; set; }
    public int Age { get; set; }
    :

    public static MyCoolAppSettings LoadFromFile(string filename)
    {

        string json = File.ReadAllText(filename);
        return Json.Convert.DeserializeObject<MyCollAppSettings>(json);
    }

    public void Save(string filename)
    {
        serialize this object into the file
    }
}

:

class Program
{
    MyCoolSettings _settings = null;

    static void Main()
    {
        string settingFileName = ...
        if (File.Exists(settingsFileName))
            _settings = MyCoolSettings.Load(settingsFileName);
        else
            _settings = new MyCoolSettings();

        :
    }
}
 
Thx, I think now I am having an architectual problem, since I have no APPSettings class that contais all properties for the tool. My classed contains properties and methods and the main class of the dll, that is instantiated from the main application (where I have no access to) has also properties and methods by definition. What do you think ?
 
You could either roll your own code to do reflection to read the values from the deserialzed instance and set them into this; or you could use the Automapper library to do the reading of the values and setting into this.

But both approaches are hacks if viewed by a modern object oriented programmer. Or would be considered as how people used to do things back in the 70s and early 80s. The irony would be using such modern implementations and concepts like serialization/deseriallizations, reflection, Automapper, etc. only to turn around and do things the primitive way. It would be like using a modern hatchet to cut wood, a lighter to start a fire, listen to music on your cellphone, but butcher the deer using some flint rock.
 
*** removed unnecessary quote ***

Thx for your hints, indeed I am coming from the 80s and 90s, started with assembler, pascal and c, but I am willing to learn. I thoutht my current approach is at least not bad. I created several classes that contain methods and the properties to make settings for those methods. All of these classes are instantiated in my plugin dll. In the GUI of the main program which uses the dll the properties appear according to the squence of the instantiation. What do you think abaut serializing only the classes where I have instances because thes classes also contain the most important settings. My problem is, meanwhile the project is such big, that it would take a lot of time an effort to make the appropriate changes. Any hints, ideas and recommendations are welcome.
 
Last edited by a moderator:
There's no need to quote the post above yours. Just like you are an old school programmer, this forum is also an old school forum where there is no need to quote the post directly above yours. It's not like the modern social media where people go crazy with quotes. :) If you must quote, just grab the specific things you want to address.

Anyway, just like you I went through a similar progression of BASIC, assembler, Forth, Pascal, C, C++, etc. In the good old days, we we could just write out a block of memory to tape or disk that had all our program state, and when we needed them back, we just loaded that back in. Those were the days. :)

Yes, serializing just those class which have the settings is the right thing to do. Do the conversion in incremental steps. Martin Fowler's book "Refactoring" is an excellent guide on how to do this incrementally. It doesn't have to be a big bang change.
 
Back
Top Bottom