Home > C#, WinRT > How to check if a file exists in a Windows 8.1 Store apps (no more exception handling)

How to check if a file exists in a Windows 8.1 Store apps (no more exception handling)

19/11/2013

In Windows 8, when we want to check for file existence, we have to use the GetFileAsync method and catch the exception.

In Windows 8.1 Store apps, this is no longer necessary: a new method, TryGetItemAsync, is available. It tries to retrive the specified file (or folder), and returns null if the item can’t be found, without rasing any exception.

So, we can write something like this:

var folder = ApplicationData.Current.LocalFolder;
var file = await folder.TryGetItemAsync("file.txt") as IStorageFile;

if (file != null)
{
    // The file exists, "file" variable contains a reference to it.
}
else
{
    // The file doesn't exist.
}

Note that, because the TryGetItemAsync method checks for both file and folders, it returns an IStorageItem object. In this example, we cast the result to IStorageFile because we actually want to retrieve a file.

Categories: C#, WinRT
  1. 22/11/2013 at 12:52

    Great news! Thanks for sharing. I just hate to try catch a simple file exists😛

  1. 20/11/2013 at 10:51
  2. 21/11/2013 at 04:20
Comments are closed.
%d bloggers like this: