The data for my app is stored in local JSON. I was originally storing it as an string app setting, but that doesn't offer enough space. So, I'm updating my app to read/write from a JSON file in local storage.
My app reads and writes the JSON at various times as a user interacts with my app and I'm getting this error a lot when reading or writing to the file:
System.IO.FileLoadException: 'The process cannot access the file because it is being used by another process.'
Here are the methods involved:
private static async Task<StorageFile> GetOrCreateJsonFile()
{
bool test = File.Exists(ApplicationData.Current.LocalFolder.Path + @"\" + jsonFileName);
if(test)
return await ApplicationData.Current.LocalFolder.GetFileAsync(jsonFileName);
else
return await ApplicationData.Current.LocalFolder.CreateFileAsync(jsonFileName);
}
private static async void StoreJsonFile(string json)
{
StorageFile jsonFile = await GetOrCreateJsonFile();
await FileIO.WriteTextAsync(jsonFile, json);
}
private static async Task<string> GetJsonFile()
{
StorageFile jsonFile = await GetOrCreateJsonFile();
return await FileIO.ReadTextAsync(jsonFile);
}
Sometimes the error is on the WriteTextAsync
, sometimes the ReadTextAsync
. There doesn't seem to be a specific point where the error occurs, just seems to happen randomly. Please let me know if there's some other way to do this to avoid the errors.