User Tools

Site Tools


notes:uwp:serialization

Serialization in UWP

Example: An exmaple of XML serialization in UWP.

The following example has two buttons:

  • The [Save Books] button serializes a bunch of book objects (represented as a BookModel class) to individual XML files, one file for each book.
  • The [Load Books] button deserializes books from XML files to a collection.
<Page x:Class="TestApp.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 
    <Grid>
        <StackPanel>
            <Button Content="Save Books" Margin="16" Click="SaveBooksButton_Click" />
            <Button Content="Load Books" Margin="16" Click="LoadBooksButton_Click" />
        </StackPanel>
    </Grid>
</Page>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Search; // StorageFileQueryResult
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
 
namespace TestApp
{
    [DataContract(Name = "Book")]
    public class BookModel
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Title { get; set; }
        [DataMember]
        public string Author { get; set; }
 
        public override string ToString()
        {
            return String.Format("Id = {0}, Title = {1}, Author = {2}", Id, Title, Author);
        }
    }
 
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
 
        private async void SaveBooksButton_Click(object sender, RoutedEventArgs e)
        {
            await SaveBookAsync(new BookModel { Id = 1, Title = "Book1", Author = "Author1" }, "book1.xml");
            await SaveBookAsync(new BookModel { Id = 2, Title = "Book2", Author = "Author2" }, "book2.xml");
            await SaveBookAsync(new BookModel { Id = 3, Title = "Book3", Author = "Author3" }, "book3.xml");
        }
 
        private async void LoadBooksButton_Click(object sender, RoutedEventArgs e)
        {
            IEnumerable<BookModel> books = await GetBooksAsync();
            foreach (BookModel book in books)
                Debug.WriteLine(book.ToString());
        }
 
        public async Task SaveBookAsync(BookModel book, string filename)
        {
            var knownTypes = new Type[]
            {
                typeof(BookModel)
            };
 
            var ser = new DataContractSerializer(typeof(BookModel), knownTypes);
 
            // Create the data file.
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
 
            using (MemoryStream ms = new MemoryStream())
            {
                // Fill the .NET memory stream with data.
                ser.WriteObject(ms, book);
 
                // Use the extension method OpenStreamForWriteAsync to obtain the .NET stream.
                using (Stream fs = await file.OpenStreamForWriteAsync())
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    await ms.CopyToAsync(fs);
                    await fs.FlushAsync();
                }
            }
        }
 
        public async Task<IEnumerable<BookModel>> GetBooksAsync()
        {
            IList<BookModel> items = new List<BookModel>();
 
            StorageFolder folder = ApplicationData.Current.LocalFolder;
 
            StorageFileQueryResult result = folder.CreateFileQuery();
            var options = new QueryOptions();
            options.IndexerOption = IndexerOption.DoNotUseIndexer; // access the file system directly
            options.FolderDepth = FolderDepth.Shallow;
            options.FileTypeFilter.Add(".xml");
            result.ApplyNewQueryOptions(options);
 
            IReadOnlyList<StorageFile> files = await result.GetFilesAsync();
 
            foreach (StorageFile file in files)
            {
                using (Stream stream = await file.OpenStreamForReadAsync())
                {
                    var ser = new DataContractSerializer(typeof(BookModel));
                    object data = await Task<object>.Run(() => ser.ReadObject(stream));
                    items.Add(data as BookModel);
                }
            }
 
            return items;
        }
    }
}
notes/uwp/serialization.txt · Last modified: 2018/04/16 by leszek