使用WPF在磁盘上存储键/值对

时间:2011-05-18 22:14:05

标签: c# wpf

我有一堆我想为我的WPF应用程序缓存的键/值对。在Silverlight中,这很简单 - 我可以这样做:

IsolatedStorageSettings userSettings = IsolatedStorageSettings.ApplicationSettings;
wombat = (string)userSettings["marsupial"];

WPF中有这样的东西吗?袋熊可能不是有袋动物,现在我想一想。那里需要做一些工作。

编辑:我想如果我可以避免将这些数据串行化,那么将会有大量的数据包含大量数据(我正在缓存网页)。 / p>

3 个答案:

答案 0 :(得分:13)

.NET Framework的桌面版本中不存在IsolatedStorageSettings,它仅在Silverlight中可用。但是,您可以在任何.NET应用程序中使用IsolatedStorage;只需将Dictionary<string, object>序列化为隔离存储中的文件。

var settings = new Dictionary<string, object>();
settings.Add("marsupial", wombat);

BinaryFormatter formatter = new BinaryFormatter();
var store = IsolatedStorageFile.GetUserStoreForAssembly();

// Save
using (var stream = store.OpenFile("settings.cfg", FileMode.OpenOrCreate, FileAccess.Write))
{
    formatter.Serialize(stream, settings);
}

// Load
using (var stream = store.OpenFile("settings.cfg", FileMode.OpenOrCreate, FileAccess.Read))
{
    settings = (Dictionary<string, object>)formatter.Deserialize(stream);
}

wombat = (string)settings["marsupial"];

答案 1 :(得分:6)

如果通过WPF,您的意思是完整的.Net运行时,那么是。使用WPF项目模板创建了一个默认的Settings类。 Settings class

答案 2 :(得分:2)

请参阅此discussion

它在WPF中不存在,但很容易从Mono的月光实现中移植(http://vega.frugalware.org/tmpgit/moon/class/System.Windows/System.IO.IsolatedStorage/IsolatedStorageSettings.cs)

    //Modifications at MoonLight's IsolatedStorageSettings.cs to make it work with WPF (whether deployed via ClickOnce or not):

// per application, per-computer, per-user
public static IsolatedStorageSettings ApplicationSettings {
  get {
    if (application_settings == null) {
      application_settings = new IsolatedStorageSettings (
        (System.Threading.Thread.GetDomain().ActivationContext!=null)?
          IsolatedStorageFile.GetUserStoreForApplication() : //for WPF, apps deployed via ClickOnce will have a non-null ActivationContext
          IsolatedStorageFile.GetUserStoreForAssembly());
    }
    return application_settings;
  }
}

// per domain, per-computer, per-user
public static IsolatedStorageSettings SiteSettings {
  get {
    if (site_settings == null) {
      site_settings = new IsolatedStorageSettings (
        (System.Threading.Thread.GetDomain().ActivationContext!=null)?
          IsolatedStorageFile.GetUserStoreForApplication() : //for WPF, apps deployed via ClickOnce will have a non-null ActivationContext
          IsolatedStorageFile.GetUserStoreForAssembly());
          //IsolatedStorageFile.GetUserStoreForSite() works only for Silverlight applications
    }
    return site_settings;
  }
}

请注意,您还应该更改该代码顶部的#if块以写入

if!SILVERLIGHT

另请参阅custom settings storage

相关问题