|
| 1 | +using System.Text; |
| 2 | + |
| 3 | +namespace LukeMauiFilePicker.Demo; |
| 4 | + |
| 5 | +public partial class MainPage : ContentPage |
| 6 | +{ |
| 7 | + static readonly Dictionary<DevicePlatform, IEnumerable<string>> FileType = new() |
| 8 | + { |
| 9 | + { DevicePlatform.Android, new[] { "text/*" } } , |
| 10 | + { DevicePlatform.iOS, new[] { ".txt", ".json" } }, |
| 11 | + { DevicePlatform.WinUI, new[] { ".txt", ".json" } } |
| 12 | + }; |
| 13 | + |
| 14 | + readonly IFilePickerService picker; |
| 15 | + public MainPage(IFilePickerService picker) |
| 16 | + { |
| 17 | + this.picker = picker; |
| 18 | + |
| 19 | + InitializeComponent(); |
| 20 | + } |
| 21 | + |
| 22 | + async Task OnFilesPickedAsync(IEnumerable<IPickFile> files) |
| 23 | + { |
| 24 | + var str = new StringBuilder(); |
| 25 | + |
| 26 | + foreach (var f in files) |
| 27 | + { |
| 28 | + using var s = await f.OpenReadAsync(); |
| 29 | + using var reader = new StreamReader(s); |
| 30 | + |
| 31 | + str.AppendLine(await reader.ReadToEndAsync()); |
| 32 | + } |
| 33 | + |
| 34 | + await MainThread.InvokeOnMainThreadAsync(() => |
| 35 | + { |
| 36 | + TextEditor.Text = str.ToString(); |
| 37 | + }); |
| 38 | + } |
| 39 | + |
| 40 | + private async void PickOne(object sender, EventArgs e) |
| 41 | + { |
| 42 | + var file = await picker.PickFileAsync("Select a file", FileType); |
| 43 | + if (file is null) { return; } |
| 44 | + |
| 45 | + await OnFilesPickedAsync(new[] { file }); |
| 46 | + } |
| 47 | + |
| 48 | + private async void PickMany(object sender, EventArgs e) |
| 49 | + { |
| 50 | + var files = await picker.PickFilesAsync("Select a file", FileType, true); |
| 51 | + if (files is null || !files.Any()) { return; } |
| 52 | + |
| 53 | + await OnFilesPickedAsync(files); |
| 54 | + } |
| 55 | + |
| 56 | + private async void Save(object sender, EventArgs e) |
| 57 | + { |
| 58 | + var bytes = Encoding.UTF8.GetBytes(TextEditor.Text ?? ""); |
| 59 | + using var memory = new MemoryStream(bytes); |
| 60 | + |
| 61 | + await picker.SaveFileAsync(new("text.txt", memory) |
| 62 | + { |
| 63 | + AndroidMimeType = "text/plain", |
| 64 | + WindowsFileTypes = ("Text files", new() { ".txt", }) |
| 65 | + }); |
| 66 | + } |
| 67 | + |
| 68 | +} |
| 69 | + |
0 commit comments