Pick Images, Videos, PDFs, and More in .NET MAUI using FilePicker
In this article, you’ll learn how to implement FilePicker in your .NET MAUI application.
The FilePicker
class lets a user pick a single or multiple files from the device.
If you worked with Xamarin, this is the same FilePicker
that has been implemented in Xamarin.Essentials
library. In .NET MAUI, it’s now built-in and comes with IFilePicker
interface so you can implement it through dependency injection if you want to.
Getting Started
To get started, you don’t need any extra setup except on Android, you must add ReadExternalStorage
permission and you’re all set.
Open the Platforms/Android/AndroidManifest.xml file and add the following:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Pick a file
Use PickAsync
method to prompt the user to pick a file from the device:
FileResult result = await FilePicker.PickAsync();
You can get the name and full path of the selected file from the result:
var fileName = result.FileName;
var fullPath = result.FullPath;
File Types
Default file types are PDFs, videos, images, or specific to PNGs or JPEGs. You can specify file types allowed by using the PickOptions
parameter. Set it through FileTypes
property:
FileResult result = await FilePicker.PickAsync(new PickOptions
{
FileTypes = FilePickerFileType.Images
});
Custom File Types
You can also specify custom file types per platform, by creating an instance of the FilePickerFileType
class.
In this example, here’s how you would specify a .doc or .docx file type:
File types may be different from one platform to the other. Android file types usually refer to as MIME types, while iOS as UTType values and WinUI as file extensions.
Here’s a demo of how it works on Windows and Android:
Pick multiple files
To pick multiple files, use FilePicker.PickMultipleAsync
method and IEnumerable<FileResult>
type is returned with all of the selected files.
Read a File
The FullPath
property doesn't always return the physical path to the file.
To get the file, use the OpenReadAsync
method.
For example, here’s how you would set an image source from the FileResult
:
FileResult result = await FilePicker.PickAsync(new PickOptions
{
FileTypes = FilePickerFileType.Images
});
if (result != null)
{
var stream = await result.OpenReadAsync();
MyImage.Source = ImageSource.FromStream(() => stream);
}
You can also implement FilePicker
with dependency injection by using the IFilePicker
interface and resolving it to FilePicker.Default
in your MauiProgram.cs
like:
builder.Services.AddSingleton(typeof(IFilePicker), FilePicker.Default);
Well, that’s it on how you can implement FilePicker
in your .NET MAUI application!
All the sample code can be found on my GitHub page, here: https://github.com/cedricgabrang/FilePickerMauiDemo
Thanks for reading! Follow me on Twitter
Cheers!