Tips and tricks for C# metro developers–The FileExistsAsync method - Eternal Coding - HTML5 / Windows / Kinect / 3D development - Site Home - MSDN Blogs

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


 

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

  • Comments 7

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))
    return;

StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
Leave a Comment
  • Please add 3 and 6 and type the answer here:
  • Post
  • So, which is more algorithmically efficient?

    O(1) try/catch around GetFileAsync, or

    O(N) enumerating all files in a directory

  • Obviously :)

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

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

  • 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.)

  • 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!

  • @Glen: Yes I agree totally!

Page 1 of 1 (7 items)