Pages

Wednesday 11 July 2012

How to implement FileExistsAsync method in C#/XAML Metro App

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

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

Source

1 comment:

  1. You just transformed an O(1) operation to an O(n) operation. Let's say I have a million files in that folder, now what? /Henrik

    ReplyDelete

Web Informer Button