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

 ApplicationDataContainer的用法

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

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

 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>


Trackback:

http://www.cnblogs.com/jing870812/archive/2012/04/05/2433753.html

posted @ 2012-07-03 16:24  my favorite  阅读(622)  评论(0编辑  收藏  举报