UWP File Management

2

Why does saving a file fail so often on UWP?

I open and read the contents of a specified file when the application is initially launched (with the help of a BackgroundWorker). Then when the application is suspending I try to save new content to the same file, however this results almost always in the following exception:

Unable to remove the file to be replaced. (Exception from HRESULT: 0x80070497)

My loading method:

private async static void SymbolLoader_DoWork(object sender, DoWorkEventArgs e)
{
        IStorageItem file = null;

        if (!UseDefault)
        {
            var folder = await StorageFolder.GetFolderFromPathAsync(SavePath);
            file = await folder.TryGetItemAsync(FileName);
        }

        if (file == null)
        {
            file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\Default.txt");
        }

        var text = await FileIO.ReadTextAsync((IStorageFile)file);

        Data = DoSomething(text);
}

My OnSuspending method:

private async void OnSuspending(object sender, SuspendingEventArgs e)
{
        var tries = 0;
        var maxTries = 10;
        var deferral = e.SuspendingOperation.GetDeferral();

        while (tries < maxTries)
        {
            var completed = await Saver.Save();

            if (completed)
                break;
            else
            {
                tries++;
                await Task.Delay(TimeSpan.FromSeconds(0.1));
            }
        }

        deferral.Complete();
}

Save method:

public static async Task<bool> Save()
{
        //some formatting etc.

        var folder = await StorageFolder.GetFolderFromPathAsync(SavePath);
        var file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);

        try
        {
            await FileIO.WriteLinesAsync(file, lines);
            return true;
        }
        catch(Exception e)
        {
            return false;
        }
}

It is critical that the data is saved, which is why I "solved" the problem by trying to save the file multiple times with some delay. However my solution, presented in the OnSuspending method, does not seem like the correct way to do this.

What is the correct approach? Thanks in advance!

c#
file
uwp
save
load
asked on Stack Overflow Sep 6, 2017 by John • edited Sep 6, 2017 by marc_s

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0