Windows 8 Study Notes (4)-Storage Data Storage

Source: Internet
Author: User

Appdata is stored in Metro Apps in two forms: Key-value pairs and storagefile.

The key-value pairs are stored in several ways:ApplicationdatacompositevalueComposite value storage,ApplicationdatacontainerContainer data storage,ApplicationdatacontainersettingsCommon container data storage.

Note that the stored values of this key-value pair can only be stored as characters. To store an object, convert itXMLOrJSONAnd other character data.

ApplicationdatacompositevalueUsage

Storage of compound values is supported.

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 settinglocalSettings.Values.Remove("exampleCompositeSetting");
 

 ApplicationdatacontainerUsage

Supports creation, deletion, enumeration, and data container hierarchy

Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;// Create a setting in a containerWindows.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 containerbool hasContainer = localSettings.Containers.ContainsKey("exampleContainer");bool hasSetting = false;if (hasContainer){   hasSetting = localSettings.Containers["exampleContainer"].Values.ContainsKey("exampleSetting");}// Delete a containerlocalSettings.DeleteContainer("exampleContainer");
 

 ApplicationdatacontainersettingsUsage

Simplest key-Value Pair Storage

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;     // Create a simple settinglocalSettings.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");

 

Storage of storagefile, stored in the form of Files

Store Data

static async public Task SaveAsync
 
  (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();            }        }
 

 

Retrieve file data

static async public Task
 
   RestoreAsync
  
   (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_;        }
  
 

The above are several data storage methods in the Metro style app. How about it? There are still some differences with Windows phone7...

 

Sort out the sequence and deserialization methods of XML/JSON data by the way.

JSON data sequence and Reverse Sequence

public static T DataContractJsonDeSerializer
 
  (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;        }
 

Sequence and reverse sequence of XML data

////// XML data object to be serialized //////
 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 ;}////// Deserialization of XML data //////
 
  
Deserialization object
 ///
 Public static t xmldeserialize
 
  
(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 );}}
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.