123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- using XGame.Framework.Asyncs;
- using System;
- using UnityEngine.Networking;
- namespace XGame.Framework.FileSystem
- {
- //internal enum ECopyMode
- //{
- // /// <summary>
- // /// 包外->包外
- // /// </summary>
- // OUTSIDE_TO_OUTSIDE,
- // /// <summary>
- // /// 包内->包外
- // /// </summary>
- // INNERASSETS_TO_OUTSIDE
- //}
- internal sealed class CopyFileAsync : Async, ICopyFileAsync
- {
- bool overwrite;
- public bool Success { get; private set; }
- public string From { get; private set; }
- public string To { get; private set; }
- public CopyFileAsync(string source, string destination, bool overwrite)
- {
- From = source;
- To = destination;
- Success = false;
- this.overwrite = overwrite;
- }
- public void Start()
- {
- if (string.IsNullOrEmpty(From))
- {
- Success = false;
- Exception = new Exception($"源文件路径为空...");
- Completed();
- return;
- }
- WebRequestCopyFile();
- }
- private void WebRequestCopyFile()
- {
- var uri = new Uri(From);
- var request = UnityWebRequest.Get(uri);
- var operation = request.SendWebRequest();
- operation.completed += (op) =>
- {
- var bRet = request.result == UnityWebRequest.Result.Success && string.IsNullOrEmpty(request.error);
- if (bRet)
- {
- try
- {
- var toDir = System.IO.Path.GetDirectoryName(To);
- if (!System.IO.Directory.Exists(toDir))
- {
- System.IO.Directory.CreateDirectory(toDir);
- }
- System.IO.File.WriteAllBytes(To, request.downloadHandler.data);
- }
- catch (Exception ex)
- {
- OnThreadCompleted(new CopyThreadContext(false, ex));
- return;
- }
- }
- else
- {
- Log.Error($"CopyFileAsync failed. From:{From} To:{To} UnityWebRequest Result:{request.result} Error:{request.error}");
- }
- OnThreadCompleted(new CopyThreadContext(bRet, null));
- };
- }
- private void OnThreadCompleted(object obj)
- {
- var context = (CopyThreadContext)obj;
- Exception = context.Exception;
- Success = context.Success;
- Completed();
- }
- struct CopyThreadContext
- {
- public bool Success { get; }
- public Exception Exception { get; }
- public CopyThreadContext(bool success, Exception exception)
- {
- Success = success;
- Exception = exception;
- }
- }
- }
- }
|