Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 210
Besuglov Sergey Avatar asked Dec 20 '22 06:12

Besuglov Sergey


1 Answers

Unfortunately there is no direct method for now to check if file exists. You can try to use one of two methods:

  • get a file, and if exception is thrown then it means that file doesn't exist,
  • list all files and check if there is one with searched filename

A simple extension methods can 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 like this:

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

The second method can be little faster in case the file doesn't exist and there are few files in a folder, hence the exception is not being thrown.

like image 81
Romasz Avatar answered Dec 29 '22 12:12

Romasz