How to export and import properity settings of a tool.

c#chris

Member
Joined
Dec 10, 2024
Messages
10
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.
 
Back
Top Bottom