Search code examples
c#windows-runtimeuwpstoragefilesqlite.net

Verifying file writes in UWP C#


I'm trying to ensure that a file gets copied to another location- for SQLite reasons (see UWP App SQLite Access database in Documents Library).

Trouble is, is that if I remove access to the target StorageFile (i.e. pulling out a USB stick then trying to save), StorageFile's CopyAndReplaceAsync method won't mention if the file fails to write.

So, trying to open the file to test that it was successfully written (with GetFileFromPathAsync) throws a COM exception (since the file isn't there), but it never ends the task even after catching the error.

I'm trying to figure out if there's a better way to do this- I've tried using FileIO to do the same thing but even though the file I'm writing is in the FutureAccessList it doesn't seem to want to grant access.

Any ideas/complications/methods I'm just not using properly?

The relevant code I have is below:

try {
    if (file != null) {
        await file.CopyAndReplaceAsync(App.SaveFile);
        var newFile = await StorageFile.GetFileFromPathAsync(App.SaveFile.Path);
 }

//user prompt below

Solution

  • According to your description, it seems you want to check for the existence of a file. If so, you can use the StorageFile.IsAvailable property or the StorageFolder.TryGetItemAsync method.

    Ref Common questions and answers about files and app data, part 2: Files:

    Q. What’s the best way to check for the existence of a file?

    A. On Windows, use the StorageFile.IsAvailable property or the StorageFolder.TryGetItemAsync method, which were both introduced in Windows 8.1 for this purpose. On Windows Phone 8.1, however, these members are not available, so currently you have to call StorageFolder.GetFileAsync within a try/catch block and check for “file not found” exceptions. (This approach also works on Windows.) Note that if you’re checking to determine whether to create the file, then just use StorageFolder.CreateFileAsync with CreateCollisionOption.OpenIfExists.

    Although this article is written for Windows 8.1 and Windows Phone 8.1, it still applies to UWP apps. And in UWP, StorageFile.IsAvailable property and the StorageFolder.TryGetItemAsync method are universal APIs, they can be used in all Windows 10 devices.