c# - 在 IsolatedStorageSettings 中存储对象

标签 c# silverlight windows-phone-7 object isolatedstorage

我有一个对象要存储在 IsolatedStorageSettings 中,我不想在应用程序重新启动时重用它。

我的问题在于我出于某种原因编写的代码在重新启动时尝试访问 key 时不记得该对象。

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();
            }
        }
    }
}

然后我在 App.xaml.cs 中实例化 WindowsPhoneSettings 并为其创建一个公共(public) getter 和 setter。为了能够在整个应用程序中访问它。调试显示正确的对象存储在隔离存储中,但是当关闭应用程序并重新打开它时,隔离存储似乎是空的。我在模拟器和真实设备上都试过了。如您所见,我在设置对象时确实调用了保存方法。

我在这里做错了什么?

最佳答案

我最终将设置保存到隔离存储中的一个文件中,因为 IsolatedStorageSettings 似乎从未起作用。

所以我的代码最终是这样的:

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);
        }
    }
}

还有一个设置类,只包含我要保存的内容。这可能是:

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);
    }
}

关于c# - 在 IsolatedStorageSettings 中存储对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7415864/

相关文章:

c# - WPF:如何将大量大图像快速加载到包装面板中?

silverlight - 有没有办法判断某些代码是否在 Silverlight 单元测试框架内执行?

c# - 基于网络的 Powerpoint 编辑器和播放器

c# - 连接到 HTTPS 的 WebClient 在某些电话设备上出现 NotFound 错误

c# - sqlite数据库位置uwp

c# - 找不到我的 Entity Framework 数据库

c# - 已分配值,从未使用过,但没有编译器消息

silverlight - 如何在我准备好之前防止 Silverlight RIA 实体附加到数据上下文

windows-phone-7 - 全景标题绑定(bind)

windows-phone-7 - WP7 : EntitySet loading. 一对多关系 - 复合主键大小写