2011-05-18 82 views
6

我想为我的WPF应用程序缓存一堆键/值对。在Silverlight中,这非常简单 - 我可以这么做:使用WPF在磁盘上存储键/值对

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

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

编辑:我想如果我可以避免将它们序列化到/从集体,因为它们中会有大量的数据(我正在缓存网页)。

+0

您可以简单地使用moonlight项目提供的实现。 http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System.IO/System/IO/IsolatedStorage/IsolatedStorageSettings.cs.htm – Andreas 2011-05-18 22:24:12

回答

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"]; 
+0

只是想警告这一个,隔离存储在管理员为FIPS编码设置机器的机器上不起作用。 http://support.microsoft.com/kb/811833。你必须用这种方法来设计你自己的加密方法。 – Phil 2012-06-18 01:22:07

6

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

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块写

如果!SILVERLIGHT

也请看看这个custom settings storage

+0

你可能想给出一个解释,为什么你会使用这种方法,而不是上面使用内部.Net代码已被接受的答案。 – Phil 2012-06-18 01:24:18