Exploring File Upload in .NET MAUI: A Comprehensive Guide


The .NET Multi-platform App UI (.NET MAUI) is a cross-platform framework for creating native mobile and desktop apps, with C# and XAML. In many applications it’s one of the essential features — the ability to interact with the file system and in particular be able to choose and upload files. So, the Filepicker comes right here. This provides a simple means to enable users to pick files to upload or process.

FilePicker in .NET MAUI makes it easy to select a file on whichever platform you are targeting (Android, iOS, Windows and macOS). It takes the underlying code away and provides a common API to developers. In this article I’ll show you how to use the FilePicker for a single file upload, and multiple files upload and how to store these files in your application.

Using FilePicker

It’s part of the Microsoft.Maui.Essentials namespace, a new namespace that ships with shared code that gives you access to native features. If you want to use FilePicker, make sure you are referencing the Essentials library and that your platform specific projects have the required permissions set up.

With the FilePicker, we provide the ability for users to select files from their device. File data can be efficiently handled, and it can filter the files by type with a support for single or multiple selections. It does this by using asynchronous methods so that you don’t block the UI thread and have a pleasant user experience at the same time.

Single File Upload

Using a common requirement, that allows users to upload a single file. This can be done effortlessly with the FilePicker. You can provide the prompt to the user to choose a file, pull information on the file, and process according to needs.

Example

Here’s how you can implement a single file upload using the FilePicker:

using Microsoft.Maui.Essentials;

public async Task PickSingleFile()
{
    try
    {
        var result = await FilePicker.PickAsync();
        if (result != null)
        {
            // Access the file
            var fileStream = await result.OpenReadAsync();
            // Process the file stream as needed
        }
    }
    catch (Exception ex)
    {
        // Handle exceptions, such as when the user cancels the pick operation
    }
}

The PickAsync() method opens the file picker interface in this example. When the user chooses a file it returns a FileResult object with details about the file selected. The file you can Read or process with your application is read into a stream using the OpenReadAsync() method.

Multiple File Upload

Had to sometimes allow users to select multiple files at once and upload them at once. FilePicker makes multi file selection easy with its method of allowing it.

Example
Here’s how to implement multiple file uploads:

using Microsoft.Maui.Essentials;

public async Task PickMultipleFiles()
{
    try
    {
        var results = await FilePicker.PickMultipleAsync();
        foreach (var result in results)
        {
            // Access each file
            var fileStream = await result.OpenReadAsync();
            // Process each file stream as needed
        }
    }
    catch (Exception ex)
    {
        // Handle exceptions
    }
}

Here with PickMultipleAsync() method, users are allowed to select multiple files. The method returns collection of FileResult objects. This collection is a list of file that you can iterate through, and handle what you want to with them if necessary.

Storing File

Once you have picked the files you may want to store it locally in your application’s sandbox to use later. And that can be important for use offline or caching purposes.

Example
To store a file selected by the user, you can write it to the application’s local storage:

using Microsoft.Maui.Essentials;
using System.IO;

public async Task StoreFile()
{
    try
    {
        var result = await FilePicker.PickAsync();
        if (result != null)
        {
            var fileStream = await result.OpenReadAsync();
            var filePath = Path.Combine(FileSystem.AppDataDirectory, result.FileName);

            using (var localFileStream = File.Create(filePath))
            {
                await fileStream.CopyToAsync(localFileStream);
            }
            // The file is now stored locally at filePath
        }
    }
    catch (Exception ex)
    {
        // Handle exceptions
    }
}

In this example, once we have picked the file, we retrieve the application’s data directory with FileSystem.AppDataDirectory. We then make a new file in this directory and copy the contents from the picked file into this file. This will store the file locally and so you can access it when you need it.

Conclusion

FilePicker in .NET MAUI is an extremely powerful tool for picking a file across all platforms. The FilePicker allows you to upload one file, multiple files, or to store them locally, using a consistent and easy API. Using the examples given here, you can easily start dealing with your file handling ability in your .NET MAUI application.

Also don’t forget to provide exception handling and edge case like user cancel or permission issue, to have a robust application. The FilePicker helps to improve your application functionality and offer a better user experience.

,