ATDownloadHandler.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #if !UNITY_2017_2_OR_NEWER
  2. using System;
  3. using System.IO;
  4. using UnityEngine.Networking;
  5. namespace AnyThink.Scripts.IntegrationManager.Editor
  6. {
  7. public class ATDownloadHandler : DownloadHandlerScript
  8. {
  9. // Required by DownloadHandler base class. Called when you address the 'bytes' property.
  10. protected override byte[] GetData()
  11. {
  12. return null;
  13. }
  14. private FileStream fileStream;
  15. public ATDownloadHandler(string path) : base(new byte[2048])
  16. {
  17. var downloadDirectory = Path.GetDirectoryName(path);
  18. if (!Directory.Exists(downloadDirectory))
  19. {
  20. Directory.CreateDirectory(downloadDirectory);
  21. }
  22. try
  23. {
  24. //Open the current file to write to
  25. fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  26. }
  27. catch (Exception exception)
  28. {
  29. // MaxSdkLogger.UserError(string.Format("Failed to create file at {0}\n{1}", path, exception.Message));
  30. ATLog.logError(string.Format("Failed to create file at {0}\n{1}", path, exception.Message));
  31. }
  32. }
  33. protected override bool ReceiveData(byte[] byteFromServer, int dataLength)
  34. {
  35. if (byteFromServer == null || byteFromServer.Length < 1 || fileStream == null)
  36. {
  37. return false;
  38. }
  39. try
  40. {
  41. //Write the current data to the file
  42. fileStream.Write(byteFromServer, 0, dataLength);
  43. }
  44. catch (Exception exception)
  45. {
  46. fileStream.Close();
  47. fileStream = null;
  48. ATLog.logError(string.Format("Failed to download file{0}", exception.Message));
  49. }
  50. return true;
  51. }
  52. protected override void CompleteContent()
  53. {
  54. fileStream.Close();
  55. }
  56. }
  57. }
  58. #endif