Tips and tricks for C# metro developers–The FileExistsAsync method

Today I share with you a small (but useful) piece of code Sourire.

Indeed, for now WinRT does not provide a method to test the existence of a specific file. You can only try/catch an GetFileAsync call and it can be disappointing.

So here is a little solution:

public async static Task<bool> FileExistsAsync(this StorageFolder folder, string name)
    var files = await folder.GetFilesAsync();

    return files.Any((f)=>
        return f.Name == name;

To use it, just call the following code:

if (!await ApplicationData.Current.LocalFolder.FileExistsAsync(filename))

StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
Comments (7)

  1. Mike says:

    So, which is more algorithmically efficient?

    O(1) try/catch around GetFileAsync, or

    O(N) enumerating all files in a directory

  2. Obviously :)

    But the second version is less annoying if you activate "Break on all exceptions" :)

  3. And I can't convince myself to use a try/Catch for a non-exceptional thing

  4. Ian Griffiths says:

    You still need the try/catch block of course. The reason the API reports the non-existence of a file with an exception is that if you have a separate 'file exists' check, the file may no longer be there by the time you call GetFileAsync, because something else may have deleted it in between you reading the folder list, and opening the file.

    But I totally agree about the annoying behaviour on "break on all exceptions." (However, what I *really* want is more fine grained control of exception breaking in VS. I want an "unbreakpoint" where I can tell VS to ignore exceptions that occur in particular circumstances.)

  5. Glen says:

    Additionally, once you start getting a few hundred files in local storage this method will be very slow.

    Only use for elegant code and a low number of files!

  6. @Glen: Yes I agree totally!