[UWP]UWP App Data存储和获取
这篇博客介绍如何在UWP开发时,如何存储App Data和获取。
App Data是指用户的一些设定,偏好等。例如,App的主题,是否接收推送,离线接收消息等。需要区分下App Data和User Data,一般情况下User Data是一些文档,文件,数据库记录。
App Data的类型有Settings和Files两类。
Settings中支持的数据类型下面几种,
UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double
Boolean
Char16, String
DateTime, TimeSpan
GUID, Point, Size, Rect
ApplicationDataCompositeValue
App Data可以存储在LocalSetting,RoamingSetting中,两者的区别是LocalSetting存储在本地,RoamingSetting是存储在漫游文件夹中。另外存储在RoamingSetting中的内容可以在同一个App的多个设备上共享数据。注意,RoamingSetting的存储空间是有限的,尽量存储一些必要的信息。
LocalSetting示例:
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;// Create a setting localSettings.Values["ExampleSetting"] = "Hello Windows"; // Retrieve the setting object value = localSettings.Values["ExampleSetting"]; // Composite setting Windows.Storage.ApplicationDataCompositeValue composite = new Windows.Storage.ApplicationDataCompositeValue(); composite["intVal"] = 1; composite["strVal"] = "string"; localSettings.Values["exampleCompositeSetting"] = composite; // Retrieve composite setting Windows.Storage.ApplicationDataCompositeValue compositeValue = (Windows.Storage.ApplicationDataCompositeValue)localSettings.Values["exampleCompositeSetting"]; if(compositeValue != null) { int intVal = (int)compositeValue["intVal"]; string strVal = (string)compositeValue["strVal"]; }
RoamingSetting
Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;// Create roaming settings roamingSettings.Values["exampleSetting"] = "Hello World"; roamingSettings.Values["HighPriority"] = "65"; // Composite setting Windows.Storage.ApplicationDataCompositeValue composite = new Windows.Storage.ApplicationDataCompositeValue(); composite["intVal"] = 1; composite["strVal"] = "string"; roamingSettings.Values["exampleCompositeSetting"] = composite; // Retrive composite setting Windows.Storage.ApplicationDataCompositeValue compositeValue = (Windows.Storage.ApplicationDataCompositeValue)roamingSettings.Values["exampleCompositeSetting"]; if(compositeValue != null) { int intValue = (int)compositeValue["intVal"]; string strValue = (string)compositeValue["strVal"]; }
可以看到,Setting中的所有数据都是以key-value形式存储的。
感谢您的阅读。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。