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.
Great news! Thanks for sharing. I just hate to try catch a simple file exists 😛