Reaperino
Reaperino

Reputation: 145

FileIO.AppendTextAsync is actually overwriting

I'm using FileIO to append Json data in a LocalStorage file.

public static async Task AppendToJsonLocalStorage<T>(string filename, T objectToWrite) where T : new()
{
    StorageFolder localFolder = ApplicationData.Current.LocalFolder;

    StorageFile saveFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
    await FileIO.AppendTextAsync(saveFile, contentsToWriteToFile);
}

AppendTextAsync should only add new text at the end of the existing file, wright ?

Because when I check the file in my file explorer with a text editor it's always overwriting the former text in it.

Upvotes: 0

Views: 275

Answers (1)

mm8
mm8

Reputation: 169350

Use CreationCollisionOption.OpenIfExists instead of CreationCollisionOption.ReplaceExisting when you create the file:

StorageFile saveFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
await FileIO.AppendTextAsync(saveFile, contentsToWriteToFile);

ReplaceExisting replaces any existing file as the name suggests. Please refer to the docs for more information.

Upvotes: 3

Related Questions