Store custom application settings in XML

橙三吉。 提交于 2019-12-06 11:35:00

By default the XmlSerializer will serialize all public properties as elements; to override that you'll need to tag each property with [XmlAttribute] (from System.Xml.Serialization namespace) which will give you your desired output.

For example:

[XmlAttribute]
public string ServerName { get; set; }

[XmlAttribute]
public string Database { get; set; }

[XmlElement]
public string UserName { get; set; }

// Note: no attribute
public string UserLogin { get; set; }

will produce something like:

<xml ServerName="Value" Database="Value">
    <UserName>Value</UserName>  <!-- Note that UserName was tagged with XmlElement, which matches the default behavior -->
    <UserLogin>Value</UserLogin>
</xml>

I have a couple of suggestions. Try code more like this:

    public static void MyConfigLoad()
    {
        if (!File.Exists(myConfigFileName))
        {
            return;
        }

        XmlSerializer mySerializer = new XmlSerializer(myConfigClass.GetType());
        using (StreamReader myXmlReader = new StreamReader(myConfigFileName))
        {
            try
            {
                myConfigClass = (MyConfigClass)mySerializer.Deserialize(myXmlReader);
            }
            catch (Exception e)
            {
                MessageBox.Show("Ошибка сериализации MyConfigLoad\n" + e.ToString());
            }
        }
    }

    public static void MyConfigSave()
    {
        XmlSerializer mySerializer = new XmlSerializer(myConfigClass.GetType());
        using (StreamWriter myXmlWriter = new StreamWriter(myConfigFileName))
        {
            try
            {
                mySerializer.Serialize(myXmlWriter, myConfigClass);
            }
            catch (Exception e)
            {
                MessageBox.Show("Ошибка сериализации MyConfigSave\n" + e.ToString());
            }
        }
    }

You should put the StreamReader and StreamWriter in using blocks so that they will be disposed even if an exception occurs. Also, I suggest you always display e.ToString() instead of just e.Message, as it will display the entire exception, including any inner exceptions.

Also, File.Exists works just like FileInfo.Exists, but doesn't require you to create an instance before using it.

One final note is that you should look into using the Settings feature instead of creating your own configuration classes. That allows you to easily create type-safe settings that can be used throughout your application, and which can be per-user or per-application.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!