Search code examples
xml-serializationwindows-runtimestorage

Why my file is not saved? XmlSerializer in WinRT


I'm working with a XmlSerializer, every time a item gets added to my list I call the save method:

async public void save(List<string> eingabe)
{
    var serializer = new XmlSerializer(typeof(List<string>));

    StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
    StorageFile sampleFile = 
        await storageFolder.CreateFileAsync(speicherPfad, CreationCollisionOption.ReplaceExisting);
    var file = await sampleFile.OpenAsync(FileAccessMode.ReadWrite);

    serializer.Serialize(file.AsStreamForWrite(), eingabe);

    file.Dispose();
}

when the app starts I call the load method:

public async Task<List<string>> load()
{
    List<string> ausgabe = new List<string>();
    XmlSerializer serializer = new XmlSerializer(typeof(List<string>));

    StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
    StorageFile sampleFile = await storageFolder.CreateFileAsync(speicherPfad, CreationCollisionOption.ReplaceExisting);

    var file = await sampleFile.OpenAsync(FileAccessMode.Read);
    List<string> speicher = (List<string>)serializer.Deserialize(file.AsStreamForRead());

    file.Dispose();

    return speicher;
}

the problem: in the load method, file is always empty (Size = 0) and i dont know why


Solution

  • Probably because of this option: CreationCollisionOption.ReplaceExisting.

    As a side note, it would be a good idea to change save to return Task and await it.