public void testGetObject() { try { GetObjectRequest request = new GetObjectRequest(bucket, commonKey, localDir, localFileName); request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0} / {1} : {2:##.##}%", completed, total, completed * 100.0 / total)); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx.Message); Assert.True(false); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); Assert.True(false); } }
/// 下载对象 public void GetObject() { //.cssg-snippet-body-start:[get-object] try { string bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID string key = "exampleobject"; //对象键 string localDir = System.IO.Path.GetTempPath(); //本地文件夹 string localFileName = "my-local-temp-file"; //指定本地保存的文件名 GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置进度回调 request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { //请求失败 Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } //.cssg-snippet-body-end }
public static void AsyncGetObject(COSXML.CosXml cosXml, string bucket, string key, string localDir, string localFileName) { GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置签名有效时长 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0} / {1} : {2:##.##}%", completed, total, completed * 100.0 / total)); }); //执行请求 cosXml.GetObject(request, delegate(CosResult result) { GetObjectResult getObjectResult = result as GetObjectResult; Console.WriteLine(getObjectResult.GetResultInfo()); }, delegate(CosClientException clientEx, CosServerException serverEx) { if (clientEx != null) { QLog.D("XIAO", clientEx.Message); Console.WriteLine("CosClientException: " + clientEx.StackTrace); } if (serverEx != null) { QLog.D("XIAO", serverEx.Message); Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }); }
public void GetObject(COSXML.CosXml cosXml, string bucket, string key, string localDir, string localFileName) { try { GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置签名有效时长 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); request.SetCosProgressCallback(delegate(long completed, long total) { // Console.WriteLine(String.Format("progress = {0} / {1} : {2:##.##}%", completed, total, completed * 100.0 / total)); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx.Message); Assert.True(false); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); Assert.True(false); } }
public async Task <ResponseModel> DownObject(string key, string localDir, string localFileName) { try { string bucket = _buketName + "-" + _appid; //存储桶名称 格式:BucketName-APPID GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置签名有效时长 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); //设置进度回调 request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 GetObjectResult result = await Task.FromResult(_cosXml.GetObject(request)); return(new ResponseModel { Code = 200, Message = result.GetResultInfo() }); } catch (CosClientException clientEx) { return(new ResponseModel { Code = 0, Message = "CosClientException: " + clientEx.Message }); } catch (CosServerException serverEx) { return(new ResponseModel { Code = 0, Message = serverEx.GetInfo() }); } }
public void download(string download_dir, string key = "md5list.json") { //初始化 CosXmlConfig string appid = "1255334966"; //设置腾讯云账户的账户标识 APPID string region = "ap-beijing"; //设置一个默认的存储桶地域 CosXmlConfig config = new CosXmlConfig.Builder() .IsHttps(true) //设置默认 HTTPS 请求 .SetAppid(appid) //设置腾讯云账户的账户标识 APPID .SetRegion(region) //设置一个默认的存储桶地域 .SetDebugLog(true) //显示日志 .Build(); //创建 CosXmlConfig 对象 //方式1, 永久密钥 string secretId = Properties.Resources.TencentID; //"云 API 密钥 SecretId"; string secretKey = Properties.Resources.TencentKey; //"云 API 密钥 SecretKey"; long durationSecond = 1000; //每次请求签名有效时长,单位为秒 QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond); //初始化 CosXmlServer CosXmlServer cosXml = new CosXmlServer(config, cosCredentialProvider); try { string bucket = "thuai-1255334966"; //存储桶,格式:BucketName-APPID string localDir = System.IO.Path.GetDirectoryName(download_dir); //本地文件夹 <-------------- string localFileName = System.IO.Path.GetFileName(download_dir); //指定本地保存的文件名 <-------------- GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置签名有效时长 //request.SetSign(DateTimeOffset.UtcNow.ToString(), 1000); //设置进度回调 Dictionary <string, string> test = request.GetRequestHeaders(); request.SetCosProgressCallback(delegate(long completed, long total) { //Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { throw clientEx; } catch (COSXML.CosException.CosServerException serverEx) { throw serverEx; } }
private void GetObject() { getObjectRequest = new GetObjectRequest(bucket, key, localDir, localFileName); getObjectRequest.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); if (progressCallback != null) { getObjectRequest.SetCosProgressCallback(progressCallback); } getObjectRequest.SetRange(rangeStart, rangeEnd); getObjectRequest.SetLocalFileOffset(localFileOffset); cosXmlServer.GetObject(getObjectRequest, delegate(CosResult result) { lock (syncExit) { if (isExit) { return; } } if (UpdateTaskState(TaskState.COMPLETED)) { GetObjectResult getObjectResult = result as GetObjectResult; DownloadTaskResult downloadTaskResult = new DownloadTaskResult(); downloadTaskResult.SetResult(getObjectResult); if (successCallback != null) { successCallback(downloadTaskResult); } } }, delegate(CosClientException clientEx, CosServerException serverEx) { lock (syncExit) { if (isExit) { return; } } if (UpdateTaskState(TaskState.FAILED)) { if (failCallback != null) { failCallback(clientEx, serverEx); } } }); }
public void GetFileDow(string keyw, string name, OnProgressCallback Dwjindu, string path) { CosXmlConfig config = new CosXmlConfig.Builder() .SetConnectionTimeoutMs(SetConnectionTimeoutMs) //设置连接超时时间,单位毫秒,默认45000ms .SetReadWriteTimeoutMs(SetReadWriteTimeoutMs) //设置读写超时时间,单位毫秒,默认45000ms .IsHttps(IsHttps) //设置默认 HTTPS 请求 .SetAppid(SetAppid) //设置腾讯云账户的账户标识 APPID .SetRegion(SetRegion) //设置一个默认的存储桶地域 .Build(); string secretId = SecretId; //云 API 密钥 SecretId string secretKey = SecretKey; //云 API 密钥 SecretKey long durationSecond = 600; //每次请求签名有效时长,单位为秒 QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond); CosXml cosXml = new CosXmlServer(config, qCloudCredentialProvider); try { string bucket = "yuanguhl"; //存储桶,格式:BucketName-APPID string key = keyw; //对象在存储桶中的位置,即称对象键 string localDir = path; //本地文件夹 string localFileName = name; //指定本地保存的文件名 GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); request.Region = "ap-beijing"; //设置签名有效时长 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); //设置进度回调 request.SetCosProgressCallback(Dwjindu); //执行请求 GetObjectResult result = cosXml.GetObject(request); //请求成功 } catch (COSXML.CosException.CosClientException clientEx) { //请求失败 throw clientEx; } catch (COSXML.CosException.CosServerException serverEx) { //请求失败 throw serverEx; } }
/// 获取预签名下载链接 public void GetPresignDownloadUrl() { //.cssg-snippet-body-start:[get-presign-download-url] try { PreSignatureStruct preSignatureStruct = new PreSignatureStruct(); preSignatureStruct.appid = "1250000000"; //腾讯云账号 APPID preSignatureStruct.region = "COS_REGION"; //存储桶地域 preSignatureStruct.bucket = "examplebucket-1250000000"; //存储桶 preSignatureStruct.key = "exampleobject"; //对象键 preSignatureStruct.httpMethod = "GET"; //HTTP 请求方法 preSignatureStruct.isHttps = true; //生成 HTTPS 请求 URL preSignatureStruct.signDurationSecond = 600; //请求签名时间为600s preSignatureStruct.headers = null; //签名中需要校验的 header preSignatureStruct.queryParameters = null; //签名中需要校验的 URL 中请求参数 string requestSignURL = cosXml.GenerateSignURL(preSignatureStruct); //下载请求预签名 URL (使用永久密钥方式计算的签名 URL) string localDir = System.IO.Path.GetTempPath(); //本地文件夹 string localFileName = "my-local-temp-file"; //指定本地保存的文件名 GetObjectRequest request = new GetObjectRequest(null, null, localDir, localFileName); //设置下载请求预签名 URL request.RequestURLWithSign = requestSignURL; //设置进度回调 request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { //请求失败 Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } //.cssg-snippet-body-end }
private void syncDownloadFile(string bucket, string fileKey, string localDir, string localFileName, OnProgressCallback progressCb, OnSuccessCallback <CosResult> successCb, OnFailedCallback failedCb) { try { GetObjectRequest request = new GetObjectRequest(bucket, fileKey, localDir, localFileName); request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); request.SetCosProgressCallback(progressCb); GetObjectResult result = cosXml.GetObject(request); } catch (CosClientException clientEx) { failedCb(clientEx, null); } catch (CosServerException serverEx) { failedCb(null, serverEx); } }
/// <summary> /// 获取图片 /// </summary> /// <param name="fileKey">图片 key</param> /// <param name="localDir">本地文件夹</param> /// <param name="localFileName">本地文件名</param> /// <returns></returns> public async Task GetImage(string fileKey, string localDir, string localFileName) { var tmpFile = "tmp_" + localFileName; var tmpFilePath = localDir + "/" + tmpFile; var localFilePath = localDir + "/" + localFileName; var cosService = await buildCosService(getImageCredential, fileKey); var request = new GetObjectRequest(getImageCredential.TmpCred.Bucket, fileKey, localDir, tmpFile); request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), signValidSec); request.SetCosProgressCallback((c, t) => { double percent = (double)c / t * 100; logger.Trace("下载进度 {}%", percent.ToString("0.00")); }); try { var result = cosService.GetObject(request); //logger.Trace(result.GetResultInfo()); // 下载成功,将临时文件移动到指定位置 if (result.httpCode == 200) { File.Move(tmpFilePath, localFilePath); // 下载失败也会出现残留文件,这里将临时下载残留文件删除 } else { if (File.Exists(tmpFilePath)) { File.Delete(tmpFilePath); } throw new StorageException(result.httpMessage); } } catch (Exception e) { // 下载失败也会出现残留文件,这里将它删除 if (File.Exists(tmpFilePath)) { File.Delete(tmpFilePath); } throw e; } }
/// <summary> /// 登录按钮被点击 /// </summary> private void ucBtnExt_Login_BtnClick(object sender, EventArgs e) { ucBtnExt_Login.FillColor = Color.FromArgb(155, 155, 155); ucBtnExt_Login.Enabled = false; string ret = Verify.Login(ucTextBoxEx_Key.InputText, localVersion, IpConfig.GetMac()); if (ret.Length == 32)//登录成功 { //登录按钮消失,进度条取代,进行必要的变量的声明 ucBtnExt_Login.Visible = false; ucProcessLine.Visible = true; ucProcessLine.Location = ucBtnExt_Login.Location; string expiredTimeS = null; string diskSerialNumber = SystemConfig.GetDiskSerialNumber(); bool isDownload = false; Thread loginSuccessThread = new Thread(() => { //对userLoginData进行赋值 userLoginData.Key = ucTextBoxEx_Key.InputText; userLoginData.StatusCode = ret; expiredTimeS = Verify.GetExpired(userLoginData.Key); userLoginData.ExpiredTimeS = expiredTimeS; DateTime expiredTime = Convert.ToDateTime(userLoginData.ExpiredTimeS); userLoginData.ExpiredTime = expiredTime; //取到期时间的时间间隔 TimeSpan ts = expiredTime.Subtract(Convert.ToDateTime(GetData.GetNetDateTime())); //用网络时间进行计算 label_Status.ForeColor = Color.FromArgb(66, 66, 66); label_Status.Text = String.Format("{0}{1}天{2}时{3}分", "卡密剩余时间:", ts.Days.ToString(), ts.Hours.ToString(), ts.Minutes.ToString()); //写配置文件保存卡密 OperateIniFile.WriteIniData("Ares", "Key", Encrypt.DES(userLoginData.Key, "areskeys"), "logindata.ini"); //核心数据取COS下载数据并解析 string appCode = Verify.GetAppCore(userLoginData.StatusCode, userLoginData.Key); if (appCode == "-1") { FrmDialog.ShowDialog(this, "Ares无法下载核心云端数据\n\n点击\"确定\"按钮退出Ares软件", "Ares - 致命错误"); Environment.Exit(0); } if (appCode.Length <= 10) { FrmDialog.ShowDialog(this, "Ares下载的核心云端数据不合法\n\n点击\"确定\"按钮退出Ares软件", "Ares - 致命错误"); Environment.Exit(0); } DllDownloadData dllDownloadData = JsonConvert.DeserializeObject <DllDownloadData>(appCode); //判断文档中的 TencentCos 文件夹是否存在,不存在就新建一个 if (Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber) != true) { try { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber); } catch { FrmDialog.ShowDialog(this, "Ares申请的读写目录权限申请失败\n\n点击\"确定\"按钮退出Ares软件", "Ares - 致命错误"); Environment.Exit(0); } Console.WriteLine("TencentCos文件夹不存在,已经新建完毕"); } //文件是否已经存在,存在就不再下载,节省流量 if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber + "\\" + Decrypt.DES(dllDownloadData.LocalFileName, Decrypt.DES(webApiUrlData.Key, "actingnb"))) == true) { //文件存在,进行MD5校验,校验通过就不重新下载了 string existFileMD5 = MD5.GetMD5HashFromFile(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber + "\\" + Decrypt.DES(dllDownloadData.LocalFileName, Decrypt.DES(webApiUrlData.Key, "actingnb"))); if (existFileMD5 != "-1") //验证是否成功取到MD5 { if (existFileMD5 == Decrypt.DES(dllDownloadData.MD5, Decrypt.DES(webApiUrlData.Key, "actingnb"))) //验证MD5是否与服务器的相符 { isDownload = false; //MD5相符,不需要重新下载 ucProcessLine.Value = 100; Console.WriteLine("MD5相符,不需要重新下载"); } else { isDownload = true;//MD5不符,需要重新下载 Console.WriteLine("MD5不符,需要重新下载"); } } } else { isDownload = true;//文件不存在,进行下载 Console.WriteLine("文件不存在,进行下载"); } //云下载DLL if (isDownload == true) { string secretId = Decrypt.DES(dllDownloadData.SecretId, Decrypt.DES(webApiUrlData.Key, "actingnb")); // API SecretId string secretKey = Decrypt.DES(dllDownloadData.SecretKey, Decrypt.DES(webApiUrlData.Key, "actingnb")); // API SecretKey string region = Decrypt.DES(dllDownloadData.Region, Decrypt.DES(webApiUrlData.Key, "actingnb")); // 存储桶所在地域 CosXmlConfig config = new CosXmlConfig.Builder() //普通初始化方式 .IsHttps(true) //设置默认 HTTPS 请求 .SetRegion(region) .SetDebugLog(true) .Build(); long durationSecond = 600; //每次请求签名有效时长,单位为秒 QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond); CosXml cosXml = new CosXmlServer(config, cosCredentialProvider); try { string bucket = Decrypt.DES(dllDownloadData.Bucket, Decrypt.DES(webApiUrlData.Key, "actingnb")); //存储桶,格式:BucketName-APPID string key = Decrypt.DES(dllDownloadData.Key, Decrypt.DES(webApiUrlData.Key, "actingnb")); //对象键 string localDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber; //下载到的目录 不需要文件名 string localFileName = Decrypt.DES(dllDownloadData.LocalFileName, Decrypt.DES(webApiUrlData.Key, "actingnb")); //指定本地保存的文件名 GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置进度回调 request.SetCosProgressCallback(delegate(long completed, long total) { //Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); ucProcessLine.Value = Convert.ToInt32(completed * 100.0 / total); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (CosClientException clientEx) { //请求失败 //MessageBox.Show("CosClientException: " + clientEx); FrmDialog.ShowDialog(this, "Ares无法下载核心云端文件\n\n点击\"确定\"按钮退出Ares软件" + "CosClientException: " + clientEx, "Ares - 致命错误"); Environment.Exit(0); } catch (CosServerException serverEx) { //请求失败 //MessageBox.Show("CosServerException: " + serverEx.GetInfo()); FrmDialog.ShowDialog(this, "Ares无法下载核心云端文件\n\n点击\"确定\"按钮退出Ares软件" + "CosServerException: " + serverEx.GetInfo(), "Ares - 致命错误"); Environment.Exit(0); } //下载完成后判断文件是否已经存在,不存在就是下载失败 if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber + "\\" + Decrypt.DES(dllDownloadData.LocalFileName, Decrypt.DES(webApiUrlData.Key, "actingnb"))) == true) { //文件存在,进行MD5校验,校验通过就不重新下载了 string existFileMD5 = MD5.GetMD5HashFromFile(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber + "\\" + Decrypt.DES(dllDownloadData.LocalFileName, Decrypt.DES(webApiUrlData.Key, "actingnb"))); if (existFileMD5 != "-1") //验证是否成功取到MD5 { if (existFileMD5 != Decrypt.DES(dllDownloadData.MD5, Decrypt.DES(webApiUrlData.Key, "actingnb"))) //验证MD5是否与服务器的相符 { FrmDialog.ShowDialog(this, "Ares下载的核心云端文件与服务器不符\n\n点击\"确定\"按钮退出Ares软件", "Ares - 致命错误"); Console.WriteLine("下载的文件MD5不符"); Environment.Exit(0); } } } else { FrmDialog.ShowDialog(this, "Ares未能成功下载核心云端文件\n\n点击\"确定\"按钮退出Ares软件", "Ares - 致命错误"); //下载的文件不存在 Console.WriteLine("下载的文件不存在"); Environment.Exit(0); } } //设置用户数据,上传用户的QQ和硬件信息 List <string> onlineQQList = GetQQNumber.GetOnlineQQ();//获取在线QQ string onlineQQ = string.Empty; if (onlineQQList.Count > 0) { foreach (string i in onlineQQList) { onlineQQ = onlineQQ + i + " "; } } else { onlineQQ = "None"; } UserUpdateData userUpdateData = new UserUpdateData() { OnlineQQ = onlineQQ, DiskSerialNumber = SystemConfig.GetDiskSerialNumber(), CpuID = SystemConfig.GetCpuID(), BoardId = SystemConfig.GetBoardId() }; string setRetCode = Verify.SetUserData(userLoginData.StatusCode, userLoginData.Key, JsonConvert.SerializeObject(userUpdateData)); //载入主窗口 this.Visible = false; Application.Run(new MainForm(userLoginData)); }); loginSuccessThread.Start(); } else { //登录失败 if (ret == "-402")//判断是否需要解绑 { if (FrmDialog.ShowDialog(this, "当前卡密未在绑定的电脑上登录\n\n点击\"确定\"按钮为您打开解绑窗口来解绑新的机器码\n\n点击\"取消\"按钮取消解绑操作并回到主界面", "Ares - 卡密解绑", true) == DialogResult.OK) { HwidResetForm hwidResetForm = new HwidResetForm(Verify, ucTextBoxEx_Key.InputText, Root.HwidResetContent.Replace("*", Environment.NewLine)); hwidResetForm.ShowDialog(); ucBtnExt_Login.FillColor = Color.FromArgb(221, 31, 50); ucBtnExt_Login.Enabled = true; } else { ucBtnExt_Login.FillColor = Color.FromArgb(221, 31, 50); ucBtnExt_Login.Enabled = true; label_Status.ForeColor = Color.FromArgb(239, 51, 42); label_Status.Text = "卡密未在绑定的电脑上登录且未解绑"; } } else { ucBtnExt_Login.FillColor = Color.FromArgb(221, 31, 50); ucBtnExt_Login.Enabled = true; label_Status.ForeColor = Color.FromArgb(239, 51, 42); label_Status.Text = ErrorCodeTranslation.Get(ret); } } }
// actual get object requests with concurrency control private void GetObject(string crc64ecma) { lock (syncExit) { if (isExit) { return; } } // create dir if not exist DirectoryInfo dirInfo = new DirectoryInfo(localDir); if (!dirInfo.Exists) { dirInfo.Create(); } // concurrency control AutoResetEvent resetEvent = new AutoResetEvent(false); int retries = 0; // return last response GetObjectResult downloadResult = null; if (sliceToRemove == null) { sliceToRemove = new HashSet <int>(); } while (sliceList.Count != 0 && retries < maxRetries) { retries += 1; foreach (int partNumber in sliceList.Keys) { if (sliceToRemove.Contains(partNumber)) { continue; } DownloadSliceStruct slice; bool get_state = sliceList.TryGetValue(partNumber, out slice); if (activeTasks >= maxTasks) { resetEvent.WaitOne(); } lock (syncExit) { if (isExit) { return; } } string tmpFileName = "." + localFileName + ".cosresumable." + slice.partNumber; // clear remainance FileInfo tmpFileInfo = new FileInfo(localDir + tmpFileName); if (tmpFileInfo.Exists && tmpFileInfo.Length != (slice.sliceEnd - slice.sliceStart + 1) && localFileOffset != 0) { System.IO.File.Delete(localDir + tmpFileName); } getObjectRequest = new GetObjectRequest(bucket, key, localDir, tmpFileName); tmpFilePaths.Add(localDir + tmpFileName); getObjectRequest.SetRange(slice.sliceStart, slice.sliceEnd); if (progressCallback != null && this.sliceList.Count == 1) { getObjectRequest.SetCosProgressCallback(delegate(long completed, long total) { progressCallback(completed, total); } ); } Interlocked.Increment(ref activeTasks); cosXmlServer.GetObject(getObjectRequest, delegate(CosResult result) { Interlocked.Decrement(ref activeTasks); lock (syncExit) { if (isExit) { return; } } sliceToRemove.Add(partNumber); if (progressCallback != null && this.sliceList.Count > 1) { long completed = sliceToRemove.Count * this.sliceSize; long total = rangeEnd - rangeStart; if (completed > total) { completed = total; } progressCallback(completed, total); } downloadResult = result as GetObjectResult; resetEvent.Set(); if (resumable) { // flush done parts this.resumableInfo.slicesDownloaded.Add(slice); this.resumableInfo.Persist(resumableTaskFile); } }, delegate(CosClientException clientEx, CosServerException serverEx) { Interlocked.Decrement(ref activeTasks); lock (syncExit) { if (isExit) { return; } } // server 4xx throw and stop if (serverEx != null && serverEx.statusCode < 500) { throw serverEx; if (failCallback != null) { failCallback(null, serverEx); } return; } // client cannot connect, just retry if (clientEx != null) { gClientExp = clientEx; } resetEvent.Set(); } ); } while (activeTasks != 0) { Thread.Sleep(100); } // remove success parts foreach (int partNumber in sliceToRemove) { sliceList.Remove(partNumber); } } if (this.sliceList.Count != 0) { if (gClientExp != null) { throw gClientExp; } COSXML.CosException.CosClientException clientEx = new COSXML.CosException.CosClientException ((int)CosClientError.InternalError, "max retries " + retries + " excceed, download fail"); throw clientEx; if (UpdateTaskState(TaskState.Failed)) { if (failCallback != null) { failCallback(clientEx, null); } } return; } // file merge FileMode fileMode = FileMode.OpenOrCreate; FileInfo localFileInfo = new FileInfo(localDir + localFileName); if (localFileInfo.Exists && localFileOffset == 0 && localFileInfo.Length != rangeEnd - rangeStart + 1) { fileMode = FileMode.Truncate; } using (var outputStream = File.Open(localDir + localFileName, fileMode)) { outputStream.Seek(localFileOffset, 0); // sort List <string> tmpFileList = new List <string>(this.tmpFilePaths); tmpFileList.Sort(delegate(string x, string y){ int partNumber1 = int.Parse(x.Split(new string[] { "cosresumable." }, StringSplitOptions.None)[1]); int partNumber2 = int.Parse(y.Split(new string[] { "cosresumable." }, StringSplitOptions.None)[1]); return(partNumber1 - partNumber2); }); foreach (var inputFilePath in tmpFileList) { // tmp not exist, clear everything and ask for retry if (!File.Exists(inputFilePath)) { // check if download already completed if (File.Exists(localDir + localFileName)) { FileInfo fileInfo = new FileInfo(localDir + localFileName); if (fileInfo.Length == rangeEnd - rangeStart + 1) { foreach (var tmpFile in tmpFileList) { System.IO.File.Delete(tmpFile); } if (resumableTaskFile != null) { System.IO.File.Delete(resumableTaskFile); } break; } } // not completed, report fatal error foreach (var tmpFile in tmpFileList) { System.IO.File.Delete(tmpFile); } if (resumableTaskFile != null) { System.IO.File.Delete(resumableTaskFile); } if (File.Exists(localDir + localFileName)) { System.IO.File.Delete(localDir + localFileName); } COSXML.CosException.CosClientException clientEx = new COSXML.CosException.CosClientException ((int)CosClientError.InternalError, "local tmp file not exist, could be concurrent writing same file" + inputFilePath + " download again"); throw clientEx; if (failCallback != null) { failCallback(clientEx, null); } break; } using (var inputStream = File.OpenRead(inputFilePath)) { FileInfo info = new FileInfo(inputFilePath); inputStream.CopyTo(outputStream); } } tmpFileList.Clear(); tmpFilePaths.Clear(); if (UpdateTaskState(TaskState.Completed)) { var dir = new DirectoryInfo(localDir); foreach (var file in dir.EnumerateFiles("." + localFileName + ".cosresumable.*")) { file.Delete(); } if (resumableTaskFile != null) { FileInfo info = new FileInfo(resumableTaskFile); if (info.Exists) { info.Delete(); } } DownloadTaskResult downloadTaskResult = new DownloadTaskResult(); downloadTaskResult.SetResult(downloadResult); outputStream.Close(); if (successCallback != null) { successCallback(downloadTaskResult); } return; } else { // 容灾 return DownloadTaskResult downloadTaskResult = new DownloadTaskResult(); downloadTaskResult.SetResult(downloadResult); outputStream.Close(); if (successCallback != null) { successCallback(downloadTaskResult); } } } return; }