How to use the read/writeable local XML settings?

青春壹個敷衍的年華 提交于 2019-12-13 14:05:24

问题


I found something similar to what I need here: http://www.codeproject.com/KB/cs/PropertiesSettings.aspx But it does not quite do it for me. The user settings are stored in some far away location such as C:\documents and settings\[username]\local settings\application data\[your application], but I do not have access to these folders and I cannot copy the settings file from one computer to another, or to delete the file altogether. Also, it would be super-convenient to have the settings xml file right next to the app, and to copy/ship both. This is used for demo-ware (which is a legitimate type of coding task) and will be used by non-technical people in the field. I need to make this quickly, so I need to reuse some existing library and not write my own. I need to make it easy to use and be portable. The last thing I want is to get a call at midnight that says that settings do not persist when edited through the settings dialog that I will have built.

So, user settings are stored god knows where, and application settings are read-only (no go). Is there anything else that I can do? I think app.config file has multiple purposes and I think I once saw it being used the way I want, I just cannot find the link.

Let me know if something is not clear.


回答1:


You could create a class that holds your settings and then XML-serialize it:

public class Settings
{
    public string Setting1 { get; set; }
    public int Setting2 { get; set; }
}

static void SaveSettings(Settings settings)
{
    var serializer = new XmlSerializer(typeof(Settings));
    using (var stream = File.OpenWrite(SettingsFilePath))
    {
        serializer.Serialize(stream, settings);
    }
}

static Settings LoadSettings()
{
    if (!File.Exists(SettingsFilePath))
        return new Settings();

    var serializer = new XmlSerializer(typeof(Settings));
    using (var stream = File.OpenRead(SettingsFilePath))
    {
        return (Settings)serializer.Deserialize(stream);
    }
}


来源:https://stackoverflow.com/questions/6402975/how-to-use-the-read-writeable-local-xml-settings

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