I'm not able to save to the isolated storage?

浪尽此生 提交于 2019-12-02 18:15:44

问题


I'm trying to save my model in isolated storage:

var settings = IsolatedStorageSettings.ApplicationSettings;

CurrentPlaceNowModel model = new CurrentPlaceNowModel();

settings.TryGetValue<CurrentPlaceNowModel>("model", out model);

if (model == null)
{
    MessageBox.Show("NULL");
    settings.Add("model", new CurrentPlaceNowModel());
    settings.Save();
}
else
    MessageBox.Show("NOT NULL");

When I start the emu i ofcourse the "NULL", but why do I keep getting it if I close the app on the emu and start it again from the menu (NOT starting it again in Visual Studio).

Should I not get "NOT NULL" 2nd time around?


回答1:


I'd do this differently and make a specific check to see if the key exists.

CurrentPlaceNowModel model; 

using (var settings = IsolatedStorageSettings.ApplicationSettings)
{
    if (settings.Contains("MODEL"))
    {
        model = settings["MODEL"] as CurrentPlaceNowModel;
    }
    else
    {
        model = new CurrentPlaceNowModel();
        settings.Add("MODEL", model);    
        settings.Save();
    }
}

This pattern of working with IsolatedStorage definitely works.

The only reason that this wouldn't work would be if CurrentPlaceNowModel could not be serialized with the DataContractSerializer. This is what the ApplicationSettings uses internally to serialize objects.
You can test this by serialising it this way yourself to see what happens.




回答2:


I've just noticed what you've done wrong:

if (model == null)
{
    MessageBox.Show("NULL");
    settings.Add("model", model);
}

That's going to be equivalent to calling settings.Add("model", null) - so how would you expect to get a non-null value out later? I suspect you want:

CurrentPlaceNowModel model;

if (!settings.TryGetValue<CurrentPlaceNowModel>("model", out model))
{
    model = new CurrentPlaceNowModel();
    settings.Add("model", model);
}


来源:https://stackoverflow.com/questions/9743641/im-not-able-to-save-to-the-isolated-storage

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