ReadFileAsync.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using XGame.Framework.Asyncs;
  2. using System;
  3. using UnityEngine.Networking;
  4. namespace XGame.Framework.FileSystem
  5. {
  6. internal sealed class ReadFileAsync : Async, IReadFileAsync
  7. {
  8. public string FilePath { get; private set; }
  9. public bool Success { get; private set; }
  10. public byte[] Data { get; private set; }
  11. public ReadFileAsync(string filePath)
  12. {
  13. FilePath = filePath;
  14. }
  15. public void Start()
  16. {
  17. if (string.IsNullOrEmpty(FilePath))
  18. {
  19. Success = false;
  20. Exception = new Exception($"源文件路径为空...");
  21. Completed();
  22. return;
  23. }
  24. WebRequestRead();
  25. }
  26. private void WebRequestRead()
  27. {
  28. var uri = new Uri(FilePath);
  29. var request = UnityWebRequest.Get(uri);
  30. var operation = request.SendWebRequest();
  31. operation.completed += (op) =>
  32. {
  33. var bRet = request.result == UnityWebRequest.Result.Success && string.IsNullOrEmpty(request.error);
  34. if (!bRet)
  35. {
  36. Log.Error($"ReadFileAsync failed. FilePath:{FilePath} UnityWebRequest Result:{request.result} Error:{request.error}");
  37. }
  38. Success = bRet;
  39. Data = request.downloadHandler.data;
  40. Completed();
  41. };
  42. }
  43. }
  44. }