在IsolatedStorageSettings存储对象 [英] Storing objects in IsolatedStorageSettings

查看:111
本文介绍了在IsolatedStorageSettings存储对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象我想在IsolatedStorageSettings,我wan't当应用程序重新启动重用存储。

I have an object I want to store in the IsolatedStorageSettings, which I wan't to reuse when the application restarts.

我的问题在于我的代码写出于某种原因不记得试图访问时重新启动它的键时的对象。

My problem lies in that the code I have written for some reason does not remember the object when trying to access the key upon restarting it.

namespace MyNameSpace
{
    public class WindowsPhoneSettings
    {
        private const string SelectedSiteKey = "SelectedSite";
        private IsolatedStorageSettings isolatedStore = IsolatedStorageSettings.ApplicationSettings;

        private T RetrieveSetting<T>(string settingKey)
        {
            object settingValue;
            if (isolatedStore.TryGetValue(settingKey, out settingValue))
            {
                return (T)settingValue;
            }
            return default(T);
        }

        public bool AddOrUpdateValue(string Key, Object value)
        {
            bool valueChanged = false;

            if (isolatedStore.Contains(Key))
            {
                if (isolatedStore[Key] != value)
                {
                    isolatedStore[Key] = value;
                    valueChanged = true;
                }
            }
            else
            {
                isolatedStore.Add(Key, value);
                valueChanged = true;
            }
            return valueChanged;
        }

        public MobileSiteDataModel SelectedSite
        {
            get
            {
                return RetrieveSetting<MobileSiteDataModel>(SelectedSiteKey);
            }
            set
            {
                AddOrUpdateValue(SelectedSiteKey, value);
                isolatedStore.Save();
            }
        }
    }
}



我然后实例WindowsPhoneSettings在App.xaml.cs并予以getter和setter它。为了能够访问它在整个应用程序。调试这表明合适的对象被存储在独立存储区,但在关闭应用程序时再重新打开它独立存储似乎是空的。我已经试过这在模拟器和实际设备两者。正如你可以看到我称之为设置对象时节省的方法。

I then instantiate WindowsPhoneSettings in App.xaml.cs and make a public getter and setter for it. To be able to access it in the whole application. Debugging this shows that the right object gets stored in the isolated store, but when closing the app and reopening it isolated store seems to be empty. I have tried this on both the emulator and a real device. As you can see I do call the save method when setting the object.

我在做什么错在这里?

推荐答案

我最后保存设置在独立存储文件作为IsolatedStorageSettings似乎从来没有工作。

I ended up saving the settings to a file in the isolated storage as IsolatedStorageSettings never seemed to work.

所以我的代码弄成这个样子:

So my code ended up like this:

public class PhoneSettings
{
    private const string SettingsDir = "settingsDir";
    private const string SettingsFile = "settings.xml";

    public void SetSettings(Settings settings)
    {
        SaveSettingToFile<Settings>(SettingsDir, SettingsFile, settings);
    }

    public Settings GetSettings()
    {
        return RetrieveSettingFromFile<Settings>(SettingsDir, SettingsFile);
    }

    private T RetrieveSettingFromFile<T>(string dir, string file) where T : class
    {
        IsolatedStorageFile isolatedFileStore = IsolatedStorageFile.GetUserStoreForApplication();
        if (isolatedFileStore.DirectoryExists(dir))
        {
            try
            {
                using (var stream = new IsolatedStorageFileStream(System.IO.Path.Combine(dir, file), FileMode.Open, isolatedFileStore))
                {
                    return (T)SerializationHelper.DeserializeData<T>(stream);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Could not retrieve file " + dir + "\\" + file + ". With Exception: " + ex.Message);
            }
        }
        return null;
    }

    private void SaveSettingToFile<T>(string dir, string file, T data)
    {
        IsolatedStorageFile isolatedFileStore = IsolatedStorageFile.GetUserStoreForApplication();
        if (!isolatedFileStore.DirectoryExists(dir))
            isolatedFileStore.CreateDirectory(dir);
        try
        {
            string fn = System.IO.Path.Combine(dir, file);
            if (isolatedFileStore.FileExists(fn)) isolatedFileStore.DeleteFile(fn); //mostly harmless, used because isolatedFileStore is stupid :D

            using (var stream = new IsolatedStorageFileStream(fn, FileMode.CreateNew, FileAccess.ReadWrite, isolatedFileStore))
            {
                SerializationHelper.SerializeData<T>(data, stream);
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Could not save file " + dir + "\\" + file + ". With Exception: " + ex.Message);
        }
    }
}

和只是包含设置类东西我要救。这可能是:

And a settings class just containing the stuff I want to save. This could be:

class Settings
{
    private string name;
    private int id;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public int Id
    {
        get { return id; }
        set { id = value; }
    }
}



编辑:样品如何 SerializationHelper 可以实施

public static class SerializationHelper
{
    public static void SerializeData<T>(this T obj, Stream streamObject)
    {
        if (obj == null || streamObject == null)
            return;

        var ser = new DataContractJsonSerializer(typeof(T));
        ser.WriteObject(streamObject, obj);
    }

    public static T DeserializeData<T>(Stream streamObject)
    {
        if (streamObject == null)
            return default(T);

        var ser = new DataContractJsonSerializer(typeof(T));
        return (T)ser.ReadObject(streamObject);
    }
}

这篇关于在IsolatedStorageSettings存储对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆