Base64Helper.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Windows.Storage.Streams;
  7. using Windows.Storage;
  8. namespace KdanCommon.Helpers
  9. {
  10. public static class Base64Helper
  11. {
  12. // https://stackoverflow.com/questions/18553691/metro-getting-the-base64-string-of-a-storagefile/18555063
  13. public static async Task<string> StorageFileToBase64(StorageFile file)
  14. {
  15. string base64String = "";
  16. if (file != null)
  17. {
  18. using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
  19. {
  20. using(var reader = new DataReader(fileStream.GetInputStreamAt(0)))
  21. {
  22. await reader.LoadAsync((uint)fileStream.Size);
  23. byte[] byteArray = new byte[fileStream.Size];
  24. reader.ReadBytes(byteArray);
  25. base64String = Convert.ToBase64String(byteArray);
  26. }
  27. }
  28. }
  29. return base64String;
  30. }
  31. }
  32. }