0

I have an application that I'm trying to implement the ability to load and save settings with. I got some sample code from another SO user's question and it half works, but I'm not sure what's going wrong.

I'm using XmlSerializer to save the AppSettings object to a file in the code below, and also to read the file back to the object. In the event that there is no file then it sets defaults and saves them before returning the object to the main application.

public class AppSettings
{
    static string applicationPath = AppDomain.CurrentDomain.BaseDirectory;
    string settingsFile = applicationPath + "Settings.xml";
    internal string databaseName;

    public void Save()
    {
        try
        {
            using (StreamWriter writer = new StreamWriter(settingsFile))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(AppSettings));
                serializer.Serialize(writer, this);
            }
        }
        catch
        {
        }
    }

    public AppSettings Read()
    {
        if (File.Exists(settingsFile))
        {
            try
            {
                using (StreamReader reader = new StreamReader(settingsFile))
                {
                    XmlSerializer deserializer = new XmlSerializer(typeof(AppSettings));
                    return deserializer.Deserialize(reader) as AppSettings;
                }
            }
            catch
            {
                return GetDefaults();
            }
        }
        else
        {
            return GetDefaults();
        }

    }

    public AppSettings GetDefaults()
    {
        databaseName = "DBNAME";
        Save();
        return this;
    }
}

I'm not getting any errors and a Settings.xml file is being generated, but the databaseName object doesn't appear to be being saved. Reading the file seems to work fine as well but the databaseName value is null. Checking the xml file I can't see any data except the xml metadata tags so I'm assuming there's a mistake with my approach to saving the AppSettings object in the first place.

XML file contents:

<?xml version="1.0" encoding="utf-8"?>
<AppSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
Peter Duniho
  • 62,751
  • 5
  • 84
  • 120
  • 1
    `XmlSerializer` only serializes **public** properties and fields. See: [Using XmlSerializer with private and public const properties](https://stackoverflow.com/q/429380) and [Serializing private member data](https://stackoverflow.com/q/802711). Your `AppSettings` has no public members. – dbc Oct 24 '19 at 23:07

1 Answers1

0

Ok so I've got it working by making databaseName public which I didn't necessarily want but that's ok, I'll be wrapping it in a public get; private set; property.