Share via


Xamarin.Essentials: File Picker

The FilePicker class lets a user pick a single or multiple files from the device.

Get started

To start using this API, read the getting started guide for Xamarin.Essentials to ensure the library is properly installed and set up in your projects.

To access the FilePicker functionality the following platform specific setup is required.

No additional setup required.

Tip

All methods must be called on the UI thread because permission checks and requests are automatically handled by Xamarin.Essentials.

Pick File

FilePicker.PickAsync() method enables your user to pick a file from the device. You are able to specific different PickOptions when calling the method enabling you to specify the title to display and the file types the user is allowed to pick. By default

async Task<FileResult> PickAndShow(PickOptions options)
{
    try
    {
        var result = await FilePicker.PickAsync(options);
        if (result != null)
        {
            Text = $"File Name: {result.FileName}";
            if (result.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
                result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
            {
                var stream = await result.OpenReadAsync();
                Image = ImageSource.FromStream(() => stream);
            }
        }
        
        return result;
    }
    catch (Exception ex)
    {
        // The user canceled or something went wrong
    }
    
    return null;
}

Default file types are provided with FilePickerFileType.Images, FilePickerFileType.Png, and FilePickerFilerType.Videos. You can specify custom files types when creating the PickOptions and they can be customized per platform. For example here is how you would specify specific comic file types:

var customFileType =
    new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>
    {
        { DevicePlatform.iOS, new[] { "public.my.comic.extension" } }, // or general UTType values
        { DevicePlatform.Android, new[] { "application/comics" } },
        { DevicePlatform.UWP, new[] { ".cbr", ".cbz" } },
        { DevicePlatform.Tizen, new[] { "*/*" } },
        { DevicePlatform.macOS, new[] { "cbr", "cbz" } }, // or general UTType values
    });
var options = new PickOptions
{
    PickerTitle = "Please select a comic file",
    FileTypes = customFileType,
};

Pick Multiple Files

If you desire your user to pick multiple files you can call the FilePicker.PickMultipleAsync() method. It also takes in PickOptions as a parameter to specify additional information. The results are the same as PickAsync, but instead of a single FileResult an IEnumerable<FileResult> is returned that can be iterated over.

Tip

The FullPath property does not always return the physical path to the file. To get the file, use the OpenReadAsync method.

Platform Differences

  • No platform differences.

API