문제

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 .

도움이 되었습니까?

해결책

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.

다른 팁

You can use Windows.Storage to store any file, the usage is like IO operation. MSDN

IsolatedStorage is similar to this for Windows Phone apps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top