I have installed the Community.Toolkit.Maui NuGet package and am having trouble with its SaveAsync method. When I click my page's "Save File" button it triggers the onSaveFileClicked method shown below. That method calls SaveAsync, which does prompt me for the name and location of the file, and does create the file in that folder, but the file is always empty.
For the moment I'm only running it on windows (ie, NOT simulating IOS or Android)
Here's my main page (for testing purposes I have hardcoded the file content to just "Hello world")
using CommunityToolkit.Maui.Storage;
using System.Collections;
using System.Diagnostics;
using System.Text;
namespace PrizesCalculator {
public partial class MainPage : ContentPage {
IFileSaver fileSaver;
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
public MainPage(IFileSaver fileSaver) {
InitializeComponent();
this.fileSaver = fileSaver;
}
... other stuff here
private void OnSaveFileClicked(object sender, EventArgs e) {
using var stream = new MemoryStream(Encoding.Default.GetBytes("hello world"));
fileSaver.SaveAsync("PrizeDistribution.csv", stream, cancellationTokenSource.Token);
}
}
}
Searched on Stackoverflow and other sites but did not find anything.
You can try the following code,it works on my side.
private async void OnSaveFileClicked(object sender, EventArgs e)
{
using var stream = new MemoryStream(Encoding.Default.GetBytes("hello world"));
//fileSaver.SaveAsync("PrizeDistribution.csv", stream, cancellationTokenSource.Token);
var fileSaverResult = await fileSaver.SaveAsync("PrizeDistribution.csv", stream, cancellationTokenSource.Token);
fileSaverResult.EnsureSuccess();
await Toast.Make($"File is saved: {fileSaverResult.FilePath}").Show(cancellationTokenSource.Token);
}