Search code examples
windows-store-appsfile-storage

Store class instance - Windows store application


I'm a bit new to programing a windows store app.So the question is how can I save an instance of a class in to an xml or binary file.I tried some code but it isn't working.

Hope that some one can steer me in the right direction .


Solution

  • You can serialize your instance by using this code

        /// <summary>
        /// Deserializes the XML.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml">The XML.</param>
        /// <returns>The instance</returns>
        public static T DeserializeXml<T>(this String xml)
        {
            var bytes = Encoding.UTF8.GetBytes(xml);
            using (var stream = new MemoryStream(bytes))
            {
                var serializer = new DataContractSerializer(typeof(T));
                return (T)serializer.ReadObject(stream);
            }
        }
    
        /// <summary>
        /// Serializes the specified instance.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <returns>Xml</returns>
        public static String SerializeXml(this Object instance)
        {
            using (var stream = new MemoryStream())
            {
                var serializer = new DataContractSerializer(instance.GetType());
                serializer.WriteObject(stream, instance);
                stream.Position = 0;
                using (var reader = new StreamReader(stream))
                {
                    var result = "<?xml version='1.0' encoding='UTF-8' ?>";
                    result += reader.ReadToEnd();
                    return result;
                }
            }
        }
    

    Next step is to save the serialized instance text to a file.

       var filename = "instance.txt";    
       var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
       var content = yourInstance.SerializeXml();
       await FileIO.WriteTextAsync(file, content, Windows.Storage.Streams.UnicodeEncoding.Utf8);
    

    Now there should be a file in your AppPackage-Local-Folder called instance.txt which contains the current instance serialized to xml.