BclStorageFile.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.IO;
  3. using System.Security;
  4. using System.Threading.Tasks;
  5. namespace Avalonia.Platform.Storage.FileIO;
  6. internal class BclStorageFile : IStorageBookmarkFile
  7. {
  8. public BclStorageFile(string fileName)
  9. {
  10. FileInfo = new FileInfo(fileName);
  11. }
  12. public BclStorageFile(FileInfo fileInfo)
  13. {
  14. FileInfo = fileInfo ?? throw new ArgumentNullException(nameof(fileInfo));
  15. }
  16. public FileInfo FileInfo { get; }
  17. public string Name => FileInfo.Name;
  18. public virtual bool CanBookmark => true;
  19. public Uri Path
  20. {
  21. get
  22. {
  23. try
  24. {
  25. if (FileInfo.Directory is not null)
  26. {
  27. return StorageProviderHelpers.FilePathToUri(FileInfo.FullName);
  28. }
  29. }
  30. catch (SecurityException)
  31. {
  32. }
  33. return new Uri(FileInfo.Name, UriKind.Relative);
  34. }
  35. }
  36. public Task<StorageItemProperties> GetBasicPropertiesAsync()
  37. {
  38. if (FileInfo.Exists)
  39. {
  40. return Task.FromResult(new StorageItemProperties(
  41. (ulong)FileInfo.Length,
  42. FileInfo.CreationTimeUtc,
  43. FileInfo.LastAccessTimeUtc));
  44. }
  45. return Task.FromResult(new StorageItemProperties());
  46. }
  47. public Task<IStorageFolder?> GetParentAsync()
  48. {
  49. if (FileInfo.Directory is { } directory)
  50. {
  51. return Task.FromResult<IStorageFolder?>(new BclStorageFolder(directory));
  52. }
  53. return Task.FromResult<IStorageFolder?>(null);
  54. }
  55. public Task<Stream> OpenReadAsync()
  56. {
  57. return Task.FromResult<Stream>(FileInfo.OpenRead());
  58. }
  59. public Task<Stream> OpenWriteAsync()
  60. {
  61. return Task.FromResult<Stream>(FileInfo.OpenWrite());
  62. }
  63. public virtual Task<string?> SaveBookmarkAsync()
  64. {
  65. return Task.FromResult<string?>(FileInfo.FullName);
  66. }
  67. public Task ReleaseBookmarkAsync()
  68. {
  69. // No-op
  70. return Task.CompletedTask;
  71. }
  72. protected virtual void Dispose(bool disposing)
  73. {
  74. }
  75. ~BclStorageFile()
  76. {
  77. Dispose(disposing: false);
  78. }
  79. public void Dispose()
  80. {
  81. Dispose(disposing: true);
  82. GC.SuppressFinalize(this);
  83. }
  84. }