FileSaver

The FileSaver provides the ability to select a target folder and save files to the file system.

Screenshot of a FileSaver on macOS

The following preconditions are required for the FileSaver:

If your target device API level is less than 33, add permissions to AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

When your app targets Android API level 34 and up, no additional permissions are required.

For more information about Android storage permission, please refer to the Android documentation about Manifest.permission

Basic usage

The FileSaver can be added to a .NET MAUI application in the following way.

Request permissions

Developers must manually request Permissions.StorageRead and Permissions.StorageWrite before saving files:

async Task RequestStoragePermissionsAndSaveFile(CancellationToken cancellationToken)
{
    var readPermissionStatus = await Permissions.RequestAsync<Permissions.StorageRead>();
    var writePermissionStatus = await Permissions.RequestAsync<Permissions.StorageWrite>();

    if (readPermissionStatus != PermissionStatus.Granted ||
        writePermissionStatus != PermissionStatus.Granted)
    {
        await Toast
            .Make("Storage permissions are required to save files.")
            .Show(cancellationToken);

        return;
    }

    await SaveFile(cancellationToken);
}

Save file

async Task SaveFile(CancellationToken cancellationToken)
{
    using var stream = new MemoryStream(Encoding.Default.GetBytes("Hello from the Community Toolkit!"));
    var fileSaverResult = await FileSaver.Default.SaveAsync("test.txt", stream, cancellationToken);
    if (fileSaverResult.IsSuccessful)
    {
        await Toast.Make($"The file was saved successfully to location: {fileSaverResult.FilePath}").Show(cancellationToken);
    }
    else
    {
        await Toast.Make($"The file was not saved successfully with error: {fileSaverResult.Exception.Message}").Show(cancellationToken);
    }
}

or in case the file is rather big and takes some time to be saved, you may be interested to know the progress. The progress is reported as a percentage from 0 to 100. For a stream that can't seek, only the final 100 is reported:

async Task SaveFile(CancellationToken cancellationToken)
{
    using var stream = new MemoryStream(Encoding.Default.GetBytes("Hello from the Community Toolkit!"));
    var saverProgress = new Progress<double>(percentage => ProgressBar.Progress = percentage / 100);
    var fileSaverResult = await FileSaver.Default.SaveAsync("test.txt", stream, saverProgress, cancellationToken);
    if (fileSaverResult.IsSuccessful)
    {
        await Toast.Make($"The file was saved successfully to location: {fileSaverResult.FilePath}").Show(cancellationToken);
    }
    else
    {
        await Toast.Make($"The file was not saved successfully with error: {fileSaverResult.Exception.Message}").Show(cancellationToken);
    }
}

Note

Earlier versions reported the progress as a fraction from 0 to 1 while the file was saved, and then 100. If your app uses the progress as a fraction, divide it by 100, as the example above does.

Methods

Method Description
SaveAsync Asks for permission, allows selecting a folder and saving files to the file system.

FileSaverResult

The result returned from the SaveAsync method. This can be used to verify whether the save was successful, check where the file was saved, and also access any exceptions that may have occurred during the save.

Properties

Property Type Description
FilePath string The location on the disk where the file was saved. On Android, when the user saves the file with a documents provider that doesn't tell the path of the file, such as a cloud provider, the save is successful and FilePath is the content:// URI of the document. Open it with the Android ContentResolver instead of the System.IO classes.
Exception Exception Gets the Exception if the save operation fails.
IsSuccessful bool Gets a value determining whether the operation was successful.
IsCancelled bool Gets a value determining whether the operation was cancelled.

Methods

Method Description
EnsureSuccess Verifies whether the save operation was successful.

Warning

EnsureSuccess will throw an Exception if the save operation is unsuccessful.

Dependency Registration

In case you want to inject a service, you first need to register it. Update MauiProgram.cs with the next changes:

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
			.UseMauiCommunityToolkit();

		builder.Services.AddSingleton<IFileSaver>(FileSaver.Default);
        return builder.Build();
    }
}

Now you can inject the service like this:

public partial class MainPage : ContentPage
{
    private readonly IFileSaver fileSaver;

	public MainPage(IFileSaver fileSaver)
	{
		InitializeComponent();
        this.fileSaver = fileSaver;
	}
	
	public async void SaveFile(object sender, EventArgs args)
	{
		using var stream = new MemoryStream(Encoding.Default.GetBytes("Hello from the Community Toolkit!"));
        var fileSaverResult = await fileSaver.SaveAsync("test.txt", stream, cancellationToken);
        fileSaverResult.EnsureSuccess();
        await Toast.Make($"File is saved: {fileSaverResult.FilePath}").Show(cancellationToken);
	}
}

Examples

You can find an example of FileSaver in action in the .NET MAUI Community Toolkit Sample Application.

API

You can find the source code for FileSaver over on the .NET MAUI Community Toolkit GitHub repository.