Windows 8学习笔记(四)--Storage数据存储

AppData在Metro App中的存储主要由两种形式,一种是键值对的形式,还有一种是StorageFile文件的存储形式。

其中键值对形式的存储又分几种:ApplicationDataCompositeValue复合值存储、ApplicationDataContainer容器数据存储、ApplicationDataContainerSettings普通的容器数据存储。

注意这种键值对的存储值只能以字符形式存储,若要存储某对象,需转成XMLjson等其它字符数据。

ApplicationDataCompositeValue的用法

支持复合值的存储

Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
  
// Create a composite setting                Windows.Storage.ApplicationDataCompositeValue composite = new Windows.Storage.ApplicationDataCompositeValue();
composite["intVal"] = 1;
composite["strVal"] = "string";
 
localSettings.Values["exampleCompositeSetting"] = composite;
 
// Read data from a composite settingWindows.Storage.ApplicationDataCompositeValue composite = (Windows.Storage.ApplicationDataCompositeValue)localSettings.Values["exampleCompositeSetting"];
                
 // Delete a composite setting
localSettings.Values.Remove("exampleCompositeSetting"); Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
// Create a setting in a container
Windows.Storage.ApplicationDataContainer container =
   localSettings.CreateContainer("exampleContainer", Windows.Storage.ApplicationDataCreateDisposition.Always);
if (localSettings.Containers.ContainsKey("exampleContainer"))
{
   localSettings.Containers["exampleContainer"].Values["exampleSetting"] = "Hello Windows";
}
// Read data from a setting in a container
bool hasContainer = localSettings.Containers.ContainsKey("exampleContainer");
bool hasSetting = false;
if (hasContainer)
{
   hasSetting = localSettings.Containers["exampleContainer"].Values.ContainsKey("exampleSetting");
}
// Delete a container
localSettings.DeleteContainer("exampleContainer");

 ApplicationDataContainer的用法

 支持创建、删除、枚举、数据容器层次的贯穿

 

 ApplicationDataContainerSettings的用法

 最简单的键值对存储

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
     // Create a simple setting
localSettings.Values["exampleSetting"] = "Hello Windows 8";
     if (localSettings.Values.ContainsKey("exampleSetting"))
  {
       // Read data from a simple setting
       Object value = localSettings.Values["exampleSetting"];
      }              
 localSettings.Values.Remove("exampleSetting");

 

StorageFile的存储,以文件的形式进行存储

存入数据

static async public Task SaveAsync<t>(T data,string fileName)
        {
            // Get the output stream for the SessionState file.
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
            IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite);
            using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
            {
                // Serialize the Session State.
                 
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                serializer.WriteObject(outStream.AsStreamForWrite(), data);
                await outStream.FlushAsync();
            }
        }</t>

 

取文件数据

static async public Task<t> RestoreAsync<t>(string filename)
        {
            // Get the input stream for the SessionState file.
            T sessionState_ = default(T);
            try
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
                if (file == null) return sessionState_;
                IInputStream inStream = await file.OpenSequentialReadAsync();
                // Deserialize the Session State.
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));               
                sessionState_= (T)serializer.ReadObject(inStream.AsStreamForRead());               
            }
            catch (Exception)
            {
                // Restoring state is best-effort.  If it fails, the app will just come up with a new session.
                 
            }
            return sessionState_;
        }</t></t>

以上就是Metro Style App中数据存储的几种方式,怎么样,跟Windows Phone7中还是有些差别的吧。。。

 

顺便整理一下xml/json格式数据的序列与反序列化的通用方法

JSON数据的序列与反序列

public static T DataContractJsonDeSerializer<t>(string jsonString)
        {
            var ds = new DataContractJsonSerializer(typeof(T));
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ds.ReadObject(ms);
            ms.Dispose();
            return obj;
        }
 
        public static string ToJsonData(object item)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
            string result = String.Empty;
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, item);
                ms.Position = 0;
                using (StreamReader reader = new StreamReader(ms))
                {
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }</t>

XML数据的序列与反序列

/// <summary>
        /// 需要序列化XML数据对象
        /// </summary>
        /// <param name="objectToSerialize"><returns></returns>
        public static string XMLSerialize(object objectToSerialize)
        {
            string result = "";
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractSerializer serializer = new DataContractSerializer(objectToSerialize.GetType());
                serializer.WriteObject(ms, objectToSerialize);
                ms.Position = 0;
 
                using (StreamReader reader = new StreamReader(ms))
                {
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }
        
        /// <summary>
        /// XML数据反序列化
        /// </summary>
        /// <typeparam name="T">反序列化对象</typeparam>
        /// <param name="xmlstr"><returns></returns>
        public static T XMLDeserialize<t>(string xmlstr)
        {
            byte[] newBuffer = System.Text.Encoding.UTF8.GetBytes(xmlstr);
 
            if (newBuffer.Length == 0)
            {
                return default(T);
            }
            using (MemoryStream ms = new MemoryStream(newBuffer))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }</t>

posted on   ShinyTang  阅读(4008)  评论(7编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
< 2012年4月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 1 2 3 4 5
6 7 8 9 10 11 12

导航

统计

作者:LucyTangLucyTang's Blog on 博客园
出处:http://www.cnblogs.com/jing870812/

本作品由LucyTang创作,采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。 任何转载必须保留完整文章,在显要地方显示署名以及原文链接。如您有任何疑问或者授权方面的协商,请给我留言
点击右上角即可分享
微信分享提示