CopyFileAsync.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using XGame.Framework.Asyncs;
  2. using System;
  3. using UnityEngine.Networking;
  4. namespace XGame.Framework.FileSystem
  5. {
  6. //internal enum ECopyMode
  7. //{
  8. // /// <summary>
  9. // /// 包外->包外
  10. // /// </summary>
  11. // OUTSIDE_TO_OUTSIDE,
  12. // /// <summary>
  13. // /// 包内->包外
  14. // /// </summary>
  15. // INNERASSETS_TO_OUTSIDE
  16. //}
  17. internal sealed class CopyFileAsync : Async, ICopyFileAsync
  18. {
  19. bool overwrite;
  20. public bool Success { get; private set; }
  21. public string From { get; private set; }
  22. public string To { get; private set; }
  23. public CopyFileAsync(string source, string destination, bool overwrite)
  24. {
  25. From = source;
  26. To = destination;
  27. Success = false;
  28. this.overwrite = overwrite;
  29. }
  30. public void Start()
  31. {
  32. if (string.IsNullOrEmpty(From))
  33. {
  34. Success = false;
  35. Exception = new Exception($"源文件路径为空...");
  36. Completed();
  37. return;
  38. }
  39. WebRequestCopyFile();
  40. }
  41. private void WebRequestCopyFile()
  42. {
  43. var uri = new Uri(From);
  44. var request = UnityWebRequest.Get(uri);
  45. var operation = request.SendWebRequest();
  46. operation.completed += (op) =>
  47. {
  48. var bRet = request.result == UnityWebRequest.Result.Success && string.IsNullOrEmpty(request.error);
  49. if (bRet)
  50. {
  51. try
  52. {
  53. var toDir = System.IO.Path.GetDirectoryName(To);
  54. if (!System.IO.Directory.Exists(toDir))
  55. {
  56. System.IO.Directory.CreateDirectory(toDir);
  57. }
  58. System.IO.File.WriteAllBytes(To, request.downloadHandler.data);
  59. }
  60. catch (Exception ex)
  61. {
  62. OnThreadCompleted(new CopyThreadContext(false, ex));
  63. return;
  64. }
  65. }
  66. else
  67. {
  68. Log.Error($"CopyFileAsync failed. From:{From} To:{To} UnityWebRequest Result:{request.result} Error:{request.error}");
  69. }
  70. OnThreadCompleted(new CopyThreadContext(bRet, null));
  71. };
  72. }
  73. private void OnThreadCompleted(object obj)
  74. {
  75. var context = (CopyThreadContext)obj;
  76. Exception = context.Exception;
  77. Success = context.Success;
  78. Completed();
  79. }
  80. struct CopyThreadContext
  81. {
  82. public bool Success { get; }
  83. public Exception Exception { get; }
  84. public CopyThreadContext(bool success, Exception exception)
  85. {
  86. Success = success;
  87. Exception = exception;
  88. }
  89. }
  90. }
  91. }