TemporaryStorage.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. namespace QuestPDF.Helpers;
  5. internal static class TemporaryStorage
  6. {
  7. private static string? TemporaryStoragePath { get; set; }
  8. internal static string GetPath()
  9. {
  10. var path = TryGetPath();
  11. if (path == null)
  12. {
  13. throw new InvalidOperationException(
  14. "Unable to find a suitable temporary storage location. " +
  15. "Please specify it using the Settings.TemporaryStoragePath setting and ensure that the application has permissions to read and write to that location.");
  16. }
  17. return path;
  18. }
  19. internal static string? TryGetPath()
  20. {
  21. if (TemporaryStoragePath != null)
  22. return TemporaryStoragePath;
  23. var candidates = new[]
  24. {
  25. Settings.TemporaryStoragePath,
  26. Path.Combine(Path.GetTempPath(), "QuestPDF", "temp"),
  27. Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QuestPDF", "temp"),
  28. Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "QuestPDF", "temp")
  29. };
  30. TemporaryStoragePath = candidates
  31. .Where(x => x != null)
  32. .FirstOrDefault(HasPermissionsToAlterPath);
  33. return TemporaryStoragePath;
  34. }
  35. private static bool HasPermissionsToAlterPath(string path)
  36. {
  37. try
  38. {
  39. if (!Directory.Exists(path))
  40. Directory.CreateDirectory(path);
  41. var testFile = Path.Combine(path, Path.GetRandomFileName());
  42. using (var fileStream = File.Create(testFile))
  43. {
  44. fileStream.WriteByte(123); // write anything
  45. }
  46. File.Delete(testFile);
  47. return true;
  48. }
  49. catch
  50. {
  51. return false;
  52. }
  53. }
  54. }