Windows Phone 8.1 | How to determine if a file exists in a local folder?

How to determine if a file exists in a local folder (Windows.Storage.ApplicationData.Current.LocalFolder) on Windows Phone 8.1?

+4
source share
1 answer

Unfortunately, there is currently no direct method for checking for a file. You can try using one of two methods:

  • get the file, and if an exception is thrown, it means that the file does not exist,
  • list all files and check if there is a search with the desired file name

Simple extension methods might look like this:

public static class FileExtensions
{
    public static async Task<bool> FileExists(this StorageFolder folder, string fileName)
    {
        try { StorageFile file = await folder.GetFileAsync(fileName); }
        catch { return false; }
        return true;
    }

    public static async Task<bool> FileExist2(this StorageFolder folder, string fileName)
    { return (await folder.GetFilesAsync()).Any(x => x.Name.Equals(fileName)); }
}

Then you can use them as follows:

bool isFile = await ApplicationData.Current.LocalFolder.FileExists("myfile.txt");

, , .

+11

All Articles