IOUtility.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. */
  8. using System;
  9. using System.IO;
  10. using UnityEngine;
  11. namespace Meta.WitAi.Utilities
  12. {
  13. public static class IOUtility
  14. {
  15. // Log error
  16. private static void LogError(string error)
  17. {
  18. VLog.E($"IO Utility - {error}");
  19. }
  20. /// <summary>
  21. /// Creates a directory recursively if desired and returns true if successful
  22. /// </summary>
  23. /// <param name="directoryPath">The directory to be created</param>
  24. /// <param name="recursively">Will traverse parent directories if needed</param>
  25. /// <returns>Returns true if the directory exists</returns>
  26. public static bool CreateDirectory(string directoryPath, bool recursively = true)
  27. {
  28. // Null
  29. if (string.IsNullOrEmpty(directoryPath))
  30. {
  31. return false;
  32. }
  33. // Already exists
  34. if (Directory.Exists(directoryPath))
  35. {
  36. return true;
  37. }
  38. // Check parent
  39. if (recursively)
  40. {
  41. string parentDirectoryPath = Path.GetDirectoryName(directoryPath);
  42. if (!string.IsNullOrEmpty(parentDirectoryPath) && !CreateDirectory(parentDirectoryPath, true))
  43. {
  44. return false;
  45. }
  46. }
  47. try
  48. {
  49. Directory.CreateDirectory(directoryPath);
  50. }
  51. catch (Exception e)
  52. {
  53. LogError($"Create Directory Exception\nDirectory Path: {directoryPath}\n{e}");
  54. return false;
  55. }
  56. // Successfully created
  57. return true;
  58. }
  59. /// <summary>
  60. /// Deletes a directory and returns true if the directory no longer exists
  61. /// </summary>
  62. /// <param name="directoryPath">The directory to be created</param>
  63. /// <param name="forceIfFilled">Whether to force a deletion if the directory contains contents</param>
  64. /// <returns>Returns true if the directory does not exist</returns>
  65. public static bool DeleteDirectory(string directoryPath, bool forceIfFilled = true)
  66. {
  67. // Already gone
  68. if (!Directory.Exists(directoryPath))
  69. {
  70. return true;
  71. }
  72. try
  73. {
  74. Directory.Delete(directoryPath, forceIfFilled);
  75. }
  76. catch (Exception e)
  77. {
  78. LogError($"Delete Directory Exception\nDirectory Path: {directoryPath}\n{e}");
  79. return false;
  80. }
  81. // Successfully deleted
  82. return true;
  83. }
  84. }
  85. }