├── AliyunOssHelperLib ├── AliyunOssHelperLib.sln ├── AliyunOssHelperLib.v12.suo ├── AliyunOssHelperLib │ ├── AliyunOssHelperLib.csproj │ ├── OssHelper.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── packages.config └── OssDemo │ ├── App.config │ ├── App.xaml │ ├── App.xaml.cs │ ├── MainWindow.xaml │ ├── MainWindow.xaml.cs │ ├── ObjectInfo.cs │ ├── OssDemo.csproj │ ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings │ ├── ScreenShots │ ├── 1.png │ ├── 2.png │ └── 3.png │ └── packages.config ├── LICENSE └── README.md /AliyunOssHelperLib/AliyunOssHelperLib.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.40629.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AliyunOssHelperLib", "AliyunOssHelperLib\AliyunOssHelperLib.csproj", "{168931BA-558B-41E3-9030-70E9AB44D21B}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OssDemo", "OssDemo\OssDemo.csproj", "{9E6E68D3-EE34-451E-A0AB-A70CB01A38F2}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {168931BA-558B-41E3-9030-70E9AB44D21B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {168931BA-558B-41E3-9030-70E9AB44D21B}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {168931BA-558B-41E3-9030-70E9AB44D21B}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {168931BA-558B-41E3-9030-70E9AB44D21B}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {9E6E68D3-EE34-451E-A0AB-A70CB01A38F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {9E6E68D3-EE34-451E-A0AB-A70CB01A38F2}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {9E6E68D3-EE34-451E-A0AB-A70CB01A38F2}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {9E6E68D3-EE34-451E-A0AB-A70CB01A38F2}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /AliyunOssHelperLib/AliyunOssHelperLib.v12.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhaotianff/aliyun-oss-csharp-Helper/387313672882353814fa31f396bb80f6d52a91b3/AliyunOssHelperLib/AliyunOssHelperLib.v12.suo -------------------------------------------------------------------------------- /AliyunOssHelperLib/AliyunOssHelperLib/AliyunOssHelperLib.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {168931BA-558B-41E3-9030-70E9AB44D21B} 8 | Library 9 | Properties 10 | AliyunOssHelperLib 11 | AliyunOssHelperLib 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\Aliyun.OSS.SDK.2.8.0\lib\Aliyun.OSS.dll 35 | True 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 60 | -------------------------------------------------------------------------------- /AliyunOssHelperLib/AliyunOssHelperLib/OssHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Aliyun.OSS; 7 | using Aliyun.OSS.Common; 8 | using Aliyun.OSS.Util; 9 | using System.IO; 10 | using System.Threading; 11 | 12 | namespace ZtiLib 13 | { 14 | public class OssHelper 15 | { 16 | private string accessKeyID; 17 | private string accessKeySecret; 18 | private string endpoint; 19 | private string bucketName; 20 | private OssException lastError; 21 | private bool isCNameFlag = false; 22 | private IEnumerable globalSummaryList = new List(); 23 | 24 | private OssClient client; 25 | AutoResetEvent resetEvent; 26 | 27 | /// 28 | /// AccessKeyID 29 | /// 30 | public string AccessKeyID 31 | { 32 | get 33 | { 34 | return accessKeyID; 35 | } 36 | 37 | set 38 | { 39 | accessKeyID = value; 40 | } 41 | } 42 | 43 | /// 44 | /// AccessKeySecret 45 | /// 46 | public string AccessKeySecret 47 | { 48 | get 49 | { 50 | return accessKeySecret; 51 | } 52 | 53 | set 54 | { 55 | accessKeySecret = value; 56 | } 57 | } 58 | 59 | /// 60 | /// Endpoint URL 61 | /// 62 | public string Endpoint 63 | { 64 | get 65 | { 66 | return endpoint; 67 | } 68 | 69 | set 70 | { 71 | endpoint = value; 72 | } 73 | } 74 | 75 | /// 76 | /// Get Last Error 77 | /// 78 | public OssException LastError 79 | { 80 | get 81 | { 82 | return lastError; 83 | } 84 | set 85 | { 86 | lastError = value; 87 | } 88 | } 89 | 90 | /// 91 | /// BucketName 92 | /// 93 | public string BucketName 94 | { 95 | get 96 | { 97 | return bucketName; 98 | } 99 | 100 | set 101 | { 102 | bucketName = value; 103 | } 104 | } 105 | 106 | #region Initialization 107 | 108 | public OssHelper() 109 | { 110 | 111 | } 112 | 113 | /// 114 | /// Instantiate OssHelper Object 115 | /// 116 | /// AccessKeyID 117 | /// AccessKeySecret 118 | /// Endpoint 119 | /// BucketName 120 | /// CName Flag true-CName false-OSS Domain Name 121 | /// 使用CNAME时,无法使用ListBuckets接口。 122 | public OssHelper(string accessKeyID, string accessKeySecret, string endpoint, string bucketName, bool isCName) 123 | { 124 | this.accessKeyID = accessKeyID; 125 | this.accessKeySecret = accessKeySecret; 126 | this.endpoint = endpoint; 127 | this.bucketName = bucketName; 128 | 129 | ClientConfiguration conf = new ClientConfiguration(); 130 | conf.IsCname = isCName; 131 | isCNameFlag = isCName; 132 | 133 | client = new OssClient(endpoint, accessKeyID, accessKeySecret, conf); 134 | resetEvent= new AutoResetEvent(false); 135 | } 136 | 137 | #endregion 138 | 139 | #region Bucket 140 | 141 | /// 142 | /// CreateBucket 143 | /// 144 | /// BucketName 145 | /// result 146 | public bool CreateBucket(string bucketName) 147 | { 148 | this.bucketName = bucketName; 149 | return CreateBucket(); 150 | } 151 | 152 | /// 153 | /// CreateBucket 154 | /// 155 | /// BucketName 156 | /// result 157 | public bool CreateBucket() 158 | { 159 | try 160 | { 161 | var bucket = client.CreateBucket(bucketName); 162 | return true; 163 | } 164 | catch (OssException ex) 165 | { 166 | lastError = ex; 167 | return false; 168 | } 169 | } 170 | 171 | /// 172 | /// Get Bucket Acl 173 | /// 174 | /// 175 | public CannedAccessControlList GetBucketAcl() 176 | { 177 | AccessControlList acl = null; 178 | CannedAccessControlList accessType = CannedAccessControlList.Default; 179 | 180 | try 181 | { 182 | acl = client.GetBucketAcl(bucketName); 183 | accessType = acl.ACL; 184 | } 185 | catch (OssException ex) 186 | { 187 | lastError = ex; 188 | } 189 | return accessType; 190 | } 191 | 192 | /// 193 | /// List All Buckets 194 | /// 195 | public IEnumerable ListBuckets() 196 | { 197 | try 198 | { 199 | var buckets = client.ListBuckets(); 200 | return buckets; 201 | } 202 | catch (OssException ex) 203 | { 204 | lastError = ex; 205 | return null; 206 | } 207 | } 208 | 209 | /// 210 | /// Is Bucket Exist 211 | /// 212 | public bool IsBucketExist() 213 | { 214 | bool result = false; 215 | try 216 | { 217 | result = client.DoesBucketExist(bucketName); 218 | } 219 | catch (OssException ex) 220 | { 221 | lastError = ex; 222 | } 223 | 224 | return result; 225 | } 226 | 227 | /// 228 | /// Is Bucket Exist 229 | /// 230 | /// Bucket name 231 | public bool IsBucketExist(string _bucketName) 232 | { 233 | this.bucketName = _bucketName; 234 | return IsBucketExist(); 235 | } 236 | 237 | /// 238 | /// Set Bucket Acl 239 | /// 240 | public bool SetBucketAcl(CannedAccessControlList accessType) 241 | { 242 | try 243 | { 244 | client.SetBucketAcl(bucketName, accessType); 245 | return true; 246 | } 247 | catch (OssException ex) 248 | { 249 | lastError = ex; 250 | return false; 251 | } 252 | } 253 | 254 | /// 255 | /// Set Bucket Acl 256 | /// 257 | public bool SetBucketAcl(string bucketName, CannedAccessControlList accessType) 258 | { 259 | this.bucketName = bucketName; 260 | return SetBucketAcl(accessType); 261 | } 262 | 263 | /// 264 | /// Delete Bucket 265 | /// 266 | public bool DeleteBucket() 267 | { 268 | try 269 | { 270 | client.DeleteBucket(bucketName); 271 | return true; 272 | } 273 | catch (OssException ex) 274 | { 275 | lastError = ex; 276 | return false; 277 | } 278 | } 279 | 280 | /// 281 | /// Delete Bucket 282 | /// 283 | public bool DeleteBucket(string bucketName) 284 | { 285 | this.bucketName = bucketName; 286 | return DeleteBucket(); 287 | } 288 | 289 | #endregion 290 | 291 | #region Upload 292 | 293 | /// 294 | /// Upload string object to bucket 295 | /// 296 | /// string object 297 | /// designate object name 298 | /// 299 | public bool PutString(string str,string name) 300 | { 301 | try 302 | { 303 | byte[] binaryData = Encoding.ASCII.GetBytes(str); 304 | MemoryStream requestContent = new MemoryStream(binaryData); 305 | client.PutObject(bucketName, name, requestContent); 306 | return true; 307 | } 308 | catch (OssException ex) 309 | { 310 | lastError = ex; 311 | return false; 312 | } 313 | } 314 | 315 | /// 316 | /// Upload string object to bucket 317 | /// 318 | ///Bucket name 319 | ///string object 320 | ///designate object name 321 | /// 322 | public bool PutString(string bucketName,string str,string name) 323 | { 324 | this.bucketName = bucketName; 325 | return PutString(str,name); 326 | } 327 | 328 | 329 | /// 330 | /// Upload file object to bucket 331 | /// 332 | /// File to upload 333 | /// 334 | public bool PutFile(string filePath) 335 | { 336 | try 337 | { 338 | client.PutObject(bucketName, System.IO.Path.GetFileName(filePath), filePath); 339 | return true; 340 | } 341 | catch (OssException ex) 342 | { 343 | lastError = ex; 344 | return false; 345 | } 346 | } 347 | 348 | /// 349 | /// Upload file object to bucket 350 | /// 351 | /// File to upload 352 | /// Object key in oss 353 | /// 354 | public bool PutFile(string filePath,string objectKey) 355 | { 356 | try 357 | { 358 | client.PutObject(bucketName, objectKey, filePath); 359 | return true; 360 | } 361 | catch (OssException ex) 362 | { 363 | lastError = ex; 364 | return false; 365 | } 366 | } 367 | 368 | /// 369 | /// Upload file object to bucket 370 | /// 371 | /// File to upload 372 | /// Bucket name 373 | /// Object key in oss 374 | /// 375 | public bool PutFile(string bueketName, string filePath,string objectKey) 376 | { 377 | this.bucketName = bueketName; 378 | return PutFile(filePath,objectKey); 379 | } 380 | 381 | /// 382 | /// Upload file object to bucket with progress 383 | /// 384 | /// File to upload 385 | /// Object key in oss 386 | /// Progress event handler 387 | public void PutFileProgress(string filePath,string objectKey,EventHandler progressCallback) 388 | { 389 | try 390 | { 391 | using (var fs = File.Open(filePath, FileMode.Open)) 392 | { 393 | var putObjectRequest = new PutObjectRequest(bucketName, objectKey, fs); 394 | putObjectRequest.StreamTransferProgress += progressCallback; 395 | client.PutObject(putObjectRequest); 396 | } 397 | } 398 | catch (OssException ex) 399 | { 400 | lastError = ex; 401 | } 402 | } 403 | 404 | /// 405 | /// Upload file object to bucket with progress 406 | /// 407 | /// Bucket name 408 | /// File to upload 409 | /// Object key in oss 410 | /// Progress event handler 411 | public void PutFileProgress(string bucketName, string filePath, string objcetKey, EventHandler progressCallback) 412 | { 413 | this.bucketName = bucketName; 414 | PutFileProgress(filePath, objcetKey, progressCallback); 415 | } 416 | 417 | /// 418 | /// Put File With Md5 Check 419 | /// 420 | /// File to upload 421 | /// Object key in oss 422 | /// md5 code 423 | /// 424 | public bool PutFileWithMd5(string filePath, string objectKey,string md5) 425 | { 426 | try 427 | { 428 | using (FileStream fs = File.Open(filePath, FileMode.Open)) 429 | { 430 | md5 = OssUtils.ComputeContentMd5(fs, fs.Length); 431 | } 432 | ObjectMetadata objectMeta = new ObjectMetadata 433 | { 434 | ContentMd5 = md5 435 | }; 436 | client.PutObject(bucketName, objectKey, filePath, objectMeta); 437 | return true; 438 | } 439 | catch (OssException ex) 440 | { 441 | lastError = ex; 442 | return false; 443 | } 444 | } 445 | 446 | /// 447 | /// Put File With Md5 Check 448 | /// 449 | /// Bucket name 450 | /// File to upload 451 | /// Object key in oss 452 | /// md5 code 453 | /// 454 | public bool PutFileWithMd5(string bucketName,string filePath, string objectKey, string md5) 455 | { 456 | this.bucketName = bucketName; 457 | return PutFileWithMd5(filePath, objectKey, md5); 458 | } 459 | 460 | //TODO 461 | //PutFileWithHeader() 462 | 463 | /// 464 | /// Pub File Async 465 | /// 466 | /// Bucket Name 467 | public void PutFileAsync(string bucketName,string filePath,string objcetKey,Action act) 468 | { 469 | try 470 | { 471 | resetEvent.Reset(); 472 | 473 | using (var fs = File.Open(filePath, FileMode.Open)) 474 | { 475 | string result = "Notice user: put object finish"; 476 | ObjectMetadata metadata = new ObjectMetadata(); 477 | client.BeginPutObject(bucketName, objcetKey, fs, metadata, PutFileAsyncCallback, result.ToCharArray()); 478 | resetEvent.WaitOne(); 479 | 480 | if (act != null) 481 | act(); 482 | } 483 | } 484 | catch (OssException ex) 485 | { 486 | lastError = ex; 487 | } 488 | } 489 | 490 | /// 491 | /// Put File Async Callback 492 | /// 493 | /// IAsyncResult 494 | private void PutFileAsyncCallback(IAsyncResult ar) 495 | { 496 | try 497 | { 498 | client.EndPutObject(ar); 499 | } 500 | catch (OssException ex) 501 | { 502 | throw ex; 503 | } 504 | finally 505 | { 506 | resetEvent.Set(); 507 | } 508 | } 509 | 510 | /// 511 | /// Put File With Call Back 512 | /// 513 | /// File to upload 514 | /// Object key in oss 515 | /// 516 | private void PutObjectCallback(string filePath, string objectKey,string callbackUrl,string callbackBody) 517 | { 518 | try 519 | { 520 | var metadata = BuildCallbackMetadata(callbackUrl, callbackBody); 521 | using (var fs = File.Open(filePath, FileMode.Open)) 522 | { 523 | var putObjectRequest = new PutObjectRequest(bucketName, objectKey, fs, metadata); 524 | var result = client.PutObject(putObjectRequest); 525 | } 526 | } 527 | catch (OssException ex) 528 | { 529 | lastError = ex; 530 | } 531 | 532 | } 533 | 534 | /// 535 | /// Build Callback Metadata 536 | /// 537 | /// 538 | /// 539 | /// 540 | private static ObjectMetadata BuildCallbackMetadata(string callbackUrl, string callbackBody) 541 | { 542 | string callbackHeaderBuilder = new CallbackHeaderBuilder(callbackUrl, callbackBody).Build(); 543 | string CallbackVariableHeaderBuilder = new CallbackVariableHeaderBuilder(). 544 | AddCallbackVariable("x:var1", "x:value1").AddCallbackVariable("x:var2", "x:value2").Build(); 545 | 546 | var metadata = new ObjectMetadata(); 547 | metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder); 548 | metadata.AddHeader(HttpHeaders.CallbackVar, CallbackVariableHeaderBuilder); 549 | return metadata; 550 | } 551 | 552 | 553 | //TODO 554 | //AppendObject 555 | 556 | /// 557 | /// Put File Multi Part 558 | /// 559 | public bool PutFileMultipart(string filePath, string objectKey, int partCount) 560 | { 561 | bool putResult = true; 562 | try 563 | { 564 | var initMultiPartResult = InitiateMultipartUpload(filePath, objectKey); 565 | var requestId = initMultiPartResult.UploadId; 566 | 567 | if (initMultiPartResult.HttpStatusCode == System.Net.HttpStatusCode.OK) 568 | { 569 | List list = UploadParts(filePath, objectKey, partCount, requestId); 570 | var result = CompleteUploadPart(objectKey, requestId, list); 571 | 572 | if (result.HttpStatusCode != System.Net.HttpStatusCode.OK) 573 | putResult = false; 574 | } 575 | } 576 | catch (OssException ex) 577 | { 578 | lastError = ex; 579 | } 580 | return putResult; 581 | } 582 | 583 | 584 | private InitiateMultipartUploadResult InitiateMultipartUpload(string filePath,string objectKey) 585 | { 586 | var request = new InitiateMultipartUploadRequest(bucketName, objectKey); 587 | var result = client.InitiateMultipartUpload(request); 588 | return result; 589 | } 590 | 591 | private List UploadParts(string filePath,string objectKey,int partCount,string uploadId) 592 | { 593 | var fi = new FileInfo(filePath); 594 | var fileSize = fi.Length; 595 | var partSize = fileSize / partCount; 596 | if (fileSize % partSize != 0) 597 | { 598 | partCount++; 599 | } 600 | 601 | var partETags = new List(); 602 | using (var fs = File.Open(filePath, FileMode.Open)) 603 | { 604 | for (var i = 0; i < partCount; i++) 605 | { 606 | var skipBytes = (long)partSize * i; 607 | fs.Seek(skipBytes, 0); 608 | var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes); 609 | var request = new UploadPartRequest(bucketName, objectKey, uploadId) 610 | { 611 | InputStream = fs, 612 | PartSize = size, 613 | PartNumber = i + 1 614 | }; 615 | 616 | var result = client.UploadPart(request); 617 | 618 | partETags.Add(result.PartETag); 619 | } 620 | } 621 | return partETags; 622 | } 623 | 624 | private CompleteMultipartUploadResult CompleteUploadPart(string objectKey, string uploadId, List partETags) 625 | { 626 | CompleteMultipartUploadResult uploadResult = null; 627 | try 628 | { 629 | var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectKey, uploadId); 630 | foreach (var partETag in partETags) 631 | { 632 | completeMultipartUploadRequest.PartETags.Add(partETag); 633 | } 634 | uploadResult = client.CompleteMultipartUpload(completeMultipartUploadRequest); 635 | } 636 | catch (OssException ex) 637 | { 638 | lastError = ex; 639 | } 640 | 641 | return uploadResult; 642 | } 643 | #endregion 644 | 645 | #region Download 646 | public void GetObject(string objectKey, string folderPath) 647 | { 648 | try 649 | { 650 | string filePath = folderPath + "\\" + objectKey.Substring(objectKey.LastIndexOf("/") + 1); 651 | var file = client.GetObject(bucketName, objectKey); 652 | using (var requestStream = file.Content) 653 | { 654 | byte[] buf = new byte[1024]; 655 | var fs = File.Open(filePath, FileMode.OpenOrCreate); 656 | var len = 0; 657 | while ((len = requestStream.Read(buf, 0, 1024)) != 0) 658 | { 659 | fs.Write(buf, 0, len); 660 | } 661 | fs.Close(); 662 | } 663 | } 664 | catch (OssException ex) 665 | { 666 | lastError = ex; 667 | } 668 | } 669 | 670 | public void GetObjectPartly(string objectKey,string folderPath,int partCount) 671 | { 672 | string filePath = folderPath + "\\" + objectKey.Substring(objectKey.LastIndexOf("/") + 1); 673 | using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate)) 674 | { 675 | var bufferedStream = new BufferedStream(fileStream); 676 | var objectMetadata = client.GetObjectMetadata(bucketName, objectKey); 677 | var fileLength = objectMetadata.ContentLength; 678 | long partSize = fileLength / partCount; 679 | 680 | 681 | for (var i = 0; i < partCount; i++) 682 | { 683 | var startPos = partSize * i; 684 | var endPos = partSize * i + (partSize < (fileLength - startPos) ? partSize : (fileLength - startPos)) - 1; 685 | Download(bufferedStream, startPos, endPos, filePath, bucketName, objectKey); 686 | } 687 | bufferedStream.Flush(); 688 | } 689 | } 690 | 691 | private void Download(BufferedStream bufferedStream, long startPos, long endPos, String localFilePath, String bucketName, String fileKey) 692 | { 693 | Stream contentStream = null; 694 | try 695 | { 696 | var getObjectRequest = new GetObjectRequest(bucketName, fileKey); 697 | getObjectRequest.SetRange(startPos, endPos); 698 | var ossObject = client.GetObject(getObjectRequest); 699 | byte[] buffer = new byte[1024 * 1024]; 700 | var bytesRead = 0; 701 | bufferedStream.Seek(startPos, SeekOrigin.Begin); 702 | contentStream = ossObject.Content; 703 | while ((bytesRead = contentStream.Read(buffer, 0, buffer.Length)) > 0) 704 | { 705 | bufferedStream.Write(buffer, 0, bytesRead); 706 | } 707 | } 708 | finally 709 | { 710 | if (contentStream != null) 711 | { 712 | contentStream.Dispose(); 713 | } 714 | } 715 | } 716 | 717 | public ObjectMetadata GetObjectMetadata(string objectKey) 718 | { 719 | try 720 | { 721 | var metadata = client.GetObjectMetadata(bucketName, objectKey); 722 | 723 | } 724 | catch (OssException ex) 725 | { 726 | lastError = ex; 727 | } 728 | return null; 729 | } 730 | 731 | public bool GetObjectProgress(string objectKey,string folderPath, EventHandler progressCallback) 732 | { 733 | try 734 | { 735 | string filePath = folderPath + "\\" + objectKey.Substring(objectKey.LastIndexOf("/") + 1); 736 | var getObjectRequest = new GetObjectRequest(bucketName, objectKey); 737 | getObjectRequest.StreamTransferProgress += progressCallback; 738 | var ossObject = client.GetObject(getObjectRequest); 739 | using (var stream = ossObject.Content) 740 | { 741 | using(FileStream fs = File.Open(filePath, FileMode.OpenOrCreate)) 742 | { 743 | var buffer = new byte[1024 * 1024]; 744 | var bytesRead = 0; 745 | while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) 746 | { 747 | fs.Write(buffer, 0, bytesRead); 748 | } 749 | } 750 | } 751 | return true; 752 | } 753 | catch (OssException ex) 754 | { 755 | lastError = ex; 756 | return false; 757 | } 758 | } 759 | 760 | private static void streamProgressCallback(object sender, StreamTransferProgressArgs args) 761 | { 762 | System.Console.WriteLine("ProgressCallback - TotalBytes:{0}, TransferredBytes:{1}", 763 | args.TotalBytes, args.TransferredBytes); 764 | } 765 | 766 | #endregion 767 | 768 | #region Object Management 769 | /// 770 | /// Delete object 771 | /// 772 | /// object name 773 | /// if you want to delete folder,append "/" in the end 774 | public bool DeleteObject(string name) 775 | { 776 | try 777 | { 778 | client.DeleteObject(bucketName, name); 779 | return true; 780 | } 781 | catch (OssException ex) 782 | { 783 | lastError = ex; 784 | return false; 785 | } 786 | } 787 | 788 | /// 789 | /// Delete object 790 | /// 791 | /// Bucket name 792 | /// object name 793 | public bool DeleteObject(string bucketName, string name) 794 | { 795 | this.bucketName = bucketName; 796 | return DeleteObject(name); 797 | } 798 | 799 | public bool DeleteBucketObjects() 800 | { 801 | try 802 | { 803 | var keys = new List(); 804 | var listResult = client.ListObjects(bucketName); 805 | foreach (var summary in listResult.ObjectSummaries) 806 | { 807 | keys.Add(summary.Key); 808 | } 809 | var request = new DeleteObjectsRequest(bucketName, keys, false); 810 | client.DeleteObjects(request); 811 | return true; 812 | } 813 | catch (OssException ex) 814 | { 815 | lastError = ex; 816 | return false; 817 | } 818 | } 819 | 820 | public bool DeleteBucketObjects(string bucketName) 821 | { 822 | this.bucketName = bucketName; 823 | return DeleteBucketObjects(); 824 | } 825 | 826 | /// 827 | /// List objcets 828 | /// 829 | /// OssObjectSummary Collection 830 | public IEnumerable ListObjects() 831 | { 832 | IEnumerable summaryList = new List(); 833 | try 834 | { 835 | var listObjectsRequest = new ListObjectsRequest(bucketName); 836 | var result = client.ListObjects(listObjectsRequest); 837 | summaryList = result.ObjectSummaries; 838 | } 839 | catch (OssException ex) 840 | { 841 | lastError = ex; 842 | } 843 | return summaryList; 844 | } 845 | 846 | public IEnumerable ListObjects(string bucketName) 847 | { 848 | this.bucketName = bucketName; 849 | return ListObjects(); 850 | } 851 | 852 | public IEnumerable ListObjectsWithFilter(string prefix) 853 | { 854 | IEnumerable summaryList = new List(); 855 | try 856 | { 857 | var listObjectsRequest = new ListObjectsRequest(bucketName) 858 | { 859 | Prefix = prefix 860 | }; 861 | var result = client.ListObjects(listObjectsRequest); 862 | summaryList = result.ObjectSummaries; 863 | } 864 | catch (OssException ex) 865 | { 866 | lastError = ex; 867 | } 868 | 869 | return summaryList; 870 | } 871 | 872 | public IEnumerable ListObjectsWithFilter(string bucketName, string prefix) 873 | { 874 | this.bucketName = bucketName; 875 | return ListObjectsWithFilter(prefix); 876 | } 877 | 878 | public IEnumerable ListObjectsAsync() 879 | { 880 | try 881 | { 882 | resetEvent.Reset(); 883 | var listObjectsRequest = new ListObjectsRequest(bucketName); 884 | client.BeginListObjects(listObjectsRequest, ListObjectCallback, null); 885 | resetEvent.WaitOne(); 886 | } 887 | catch (OssException ex) 888 | { 889 | lastError = ex; 890 | } 891 | return globalSummaryList; 892 | } 893 | private void ListObjectCallback(IAsyncResult ar) 894 | { 895 | try 896 | { 897 | var result = client.EndListObjects(ar); 898 | globalSummaryList = result.ObjectSummaries; 899 | resetEvent.Set(); 900 | } 901 | catch (OssException ex) 902 | { 903 | lastError = ex; 904 | } 905 | } 906 | 907 | public IEnumerable ListObjectsAsync(string bucketName) 908 | { 909 | this.bucketName = bucketName; 910 | return ListObjectsAsync(); 911 | } 912 | 913 | public IEnumerable ListObjectWithSubDir() 914 | { 915 | List summaryList = new List(); 916 | try 917 | { 918 | ObjectListing result = null; 919 | string nextMarker = string.Empty; 920 | do 921 | { 922 | var listObjectsRequest = new ListObjectsRequest(bucketName) 923 | { 924 | Marker = nextMarker, 925 | MaxKeys = 100 926 | }; 927 | result = client.ListObjects(listObjectsRequest); 928 | summaryList.AddRange(result.ObjectSummaries); 929 | nextMarker = result.NextMarker; 930 | } while (result.IsTruncated); 931 | } 932 | catch (OssException ex) 933 | { 934 | lastError = ex; 935 | } 936 | return summaryList; 937 | } 938 | 939 | public IEnumerable ListObjectWithSubDir(string bucketName) 940 | { 941 | this.bucketName = bucketName; 942 | return ListObjectWithSubDir(); 943 | } 944 | 945 | 946 | public IEnumerable ListDirObject(string dir) 947 | { 948 | return ListObjectsWithFilter(dir + "/"); 949 | } 950 | 951 | public IEnumerable ListDirObject(string bucketName, string dir) 952 | { 953 | this.bucketName = bucketName; 954 | return ListDirObject(dir); 955 | } 956 | 957 | public IEnumerable ListObjectAndSubDir(string dir) 958 | { 959 | List summaryList = new List(); 960 | try 961 | { 962 | string prefix = ""; 963 | if (!string.IsNullOrEmpty(dir)) 964 | prefix = dir + "/"; 965 | var listObjectsRequest = new ListObjectsRequest(bucketName) 966 | { 967 | Prefix = prefix, 968 | Delimiter = "/" 969 | }; 970 | var result = client.ListObjects(listObjectsRequest); 971 | summaryList.AddRange(result.ObjectSummaries.Select(x => x.Key)); 972 | summaryList.AddRange(result.CommonPrefixes); 973 | } 974 | catch (OssException ex) 975 | { 976 | lastError = ex; 977 | } 978 | return summaryList; 979 | } 980 | 981 | public IEnumerable ListObjectAndSubDir(string bucketName,string dir) 982 | { 983 | this.bucketName = bucketName; 984 | return ListObjectAndSubDir(dir); 985 | } 986 | 987 | public bool CopyObect(string sourceKey, string targetBucket, string targetKey) 988 | { 989 | try 990 | { 991 | var metadata = new ObjectMetadata(); 992 | metadata.AddHeader(Aliyun.OSS.Util.HttpHeaders.ContentType, "text/html"); 993 | var req = new CopyObjectRequest(bucketName, sourceKey, targetBucket, targetKey) 994 | { 995 | NewObjectMetadata = metadata 996 | }; 997 | var ret = client.CopyObject(req); 998 | if (ret.HttpStatusCode == System.Net.HttpStatusCode.OK) 999 | return true; 1000 | return false; 1001 | } 1002 | catch (OssException ex) 1003 | { 1004 | lastError = ex; 1005 | return false; 1006 | } 1007 | } 1008 | 1009 | public bool CopyObject(string bucketName,string sourceKey,string targetBucket,string targetKey) 1010 | { 1011 | this.bucketName = bucketName; 1012 | return CopyObect(sourceKey, targetBucket, targetKey); 1013 | } 1014 | #endregion 1015 | 1016 | } 1017 | } 1018 | -------------------------------------------------------------------------------- /AliyunOssHelperLib/AliyunOssHelperLib/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("AliyunOssHelperLib")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("AliyunOssHelperLib")] 13 | [assembly: AssemblyCopyright("Copyright © 2018")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("63540815-12d9-4d33-8b57-f0cd5d3121bf")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /AliyunOssHelperLib/AliyunOssHelperLib/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /AliyunOssHelperLib/OssDemo/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /AliyunOssHelperLib/OssDemo/App.xaml: -------------------------------------------------------------------------------- 1 |  5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /AliyunOssHelperLib/OssDemo/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Configuration; 4 | using System.Data; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using System.Windows; 8 | 9 | namespace OssDemo 10 | { 11 | /// 12 | /// Interaction logic for App.xaml 13 | /// 14 | public partial class App : Application 15 | { 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /AliyunOssHelperLib/OssDemo/MainWindow.xaml: -------------------------------------------------------------------------------- 1 |  5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 |