Search code examples
c#uwpstoragexmlserializerstoragefile

How to use System.IO Serializers in UWP with Windows.Storage


I want to be able to have a list of class objects (List<Class>) and be able to easily write and read to a text file.

In my older Console Applications and Windows Forms applications I used to use:

List<Class> _myList = ... 
WriteToFile<List<Class>>("C:\\...\\Test.txt", Class _myList)

public static void WriteToFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
        {
            TextWriter writer = null;
            try
            {
                var serializer = new XmlSerializer(typeof(T));
                writer = new StreamWriter(filePath, append);
                serializer.Serialize(writer, objectToWrite);
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }

However this does not work in a UWP application and I have to use StorageFolder and StorageFile which works fine for writing simple text to a file like this:

StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile file= await storageFolder.GetFileAsync("Test.txt");
await FileIO.WriteTextAsync(sampleFile, "Example Write Text");

But I want to be able to use the more advanced functionality of XmlSerializer along with StreamWriter to write lists of classes to a file within my UWP application.

How can I do this?


Solution

  • You can use the Stream-based versions the methods you use, for example StreamWriter has a constructor which takes a System.IO.Stream instance.

    To get a System.IO.Stream from a StorageFile, you can use the OpenStreamForWriteAsync and OpenStreamForReadAsync extension methods, which are in the System.IO namespace on UWP:

    //add to the top of the file
    using System.IO;
    
    //in your code
    var stream = await myStorageFile.OpenStreamForWriteAsync();
    //do something, e.g.
    var streamWriter = new StreamWriter(stream);