StorageService.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using Avalonia.Controls.ApplicationLifetimes;
  2. using Avalonia.Controls;
  3. using Avalonia.Platform.Storage;
  4. using System;
  5. using System.Threading.Tasks;
  6. using Avalonia;
  7. using Avalonia.VisualTree;
  8. namespace VeloeAvaloniaKemonoPartyApp.Services
  9. {
  10. public class StorageService
  11. {
  12. protected virtual IStorageProvider Storage => _storage ??= GetTopLevel()?.StorageProvider ?? throw new NullReferenceException("No StorageProvider found.");
  13. private IStorageProvider? _storage;
  14. public async Task<string?> GetDocumentsFolderAsync()
  15. {
  16. var result = await Storage.TryGetWellKnownFolderAsync(WellKnownFolder.Documents);
  17. return result.TryGetLocalPath();
  18. }
  19. public async Task<string?> GetPicturesFolderAsync()
  20. {
  21. var result = await Storage.TryGetWellKnownFolderAsync(WellKnownFolder.Pictures);
  22. return result.TryGetLocalPath();
  23. }
  24. private TopLevel? GetTopLevel()
  25. {
  26. if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  27. {
  28. return desktop.MainWindow;
  29. }
  30. if (Application.Current?.ApplicationLifetime is ISingleViewApplicationLifetime viewApp)
  31. {
  32. var visualRoot = viewApp.MainView?.GetVisualRoot();
  33. return visualRoot as TopLevel;
  34. }
  35. return null;
  36. }
  37. }
  38. }