├── 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 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows;
7 | using System.Windows.Controls;
8 | using System.Windows.Data;
9 | using System.Windows.Documents;
10 | using System.Windows.Input;
11 | using System.Windows.Media;
12 | using System.Windows.Media.Imaging;
13 | using System.Windows.Navigation;
14 | using System.Windows.Shapes;
15 | using System.ComponentModel;
16 | using Microsoft.Win32;
17 | using System.Collections.ObjectModel;
18 | using Aliyun.OSS;
19 |
20 | namespace OssDemo
21 | {
22 | ///
23 | /// Interaction logic for MainWindow.xaml
24 | ///
25 | public partial class MainWindow : Window
26 | {
27 | ObservableCollection uploadList = new ObservableCollection();
28 | ObservableCollection downloadList = new ObservableCollection();
29 | ZtiLib.OssHelper ossHelper;
30 |
31 | int globalIndex = 0;
32 | double step = 0;
33 | double remain = 0;
34 |
35 | public string Key { get; set; }
36 |
37 | public string Secret { get; set; }
38 |
39 | public string EndPoint { get; set; }
40 |
41 | public string BucketName { get; set; }
42 |
43 | public string DownloadBucketName { get; set; }
44 |
45 | public MainWindow()
46 | {
47 | InitializeComponent();
48 | this.combox_EndPoint.ItemsSource = EndPointList();
49 | this.listview_Upload.ItemsSource = uploadList;
50 | }
51 |
52 | private void btn_AddFile_Click(object sender, RoutedEventArgs e)
53 | {
54 | OpenFileDialog openDialog = new OpenFileDialog();
55 | openDialog.Filter = "全部文件|*.*";
56 | openDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
57 | if(openDialog.ShowDialog() == true)
58 | {
59 | AddFile(openDialog.FileName);
60 | }
61 | }
62 |
63 | private void btn_AddFolder_Click(object sender, RoutedEventArgs e)
64 | {
65 | System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog();
66 | folderDialog.RootFolder = Environment.SpecialFolder.Desktop;
67 |
68 | if (folderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
69 | {
70 | List list = System.IO.Directory.GetFiles(folderDialog.SelectedPath).ToList();
71 | list.ForEach(x => AddFile(x));
72 | }
73 | }
74 |
75 | private void btn_Upload_Click(object sender, RoutedEventArgs e)
76 | {
77 | remain = 100 % uploadList.Count;
78 | step = 100 / uploadList.Count;
79 |
80 | System.Threading.Thread thread = new System.Threading.Thread(Upload);
81 | thread.IsBackground = true;
82 | thread.Start();
83 | }
84 |
85 | private void AddFile(string fileName)
86 | {
87 |
88 | System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
89 | ObjectInfo objectInfo = new ObjectInfo()
90 | {
91 | FileName = fileInfo.Name,
92 | FilePath = fileInfo.FullName,
93 | FileSize = (fileInfo.Length /1024).ToString("0.00") + "KB",
94 | FileType = fileInfo.Extension,
95 | Progress = "0%"
96 | };
97 |
98 | uploadList.Add(objectInfo);
99 | }
100 |
101 | public void Upload()
102 | {
103 | if(uploadList.Count == 0)
104 | {
105 | Dispatcher.Invoke(() => {
106 | MessageBox.Show("请先添加文件");
107 | });
108 | return;
109 | }
110 |
111 | if(string.IsNullOrEmpty(Key) || string.IsNullOrEmpty(Secret))
112 | {
113 | Dispatcher.Invoke(() => {
114 | MessageBox.Show("请先配置访问密钥");
115 | this.tab.SelectedIndex = 2;
116 | });
117 | return;
118 | }
119 |
120 | string folder = "";
121 |
122 | Dispatcher.Invoke(() => {
123 | ossHelper.BucketName = this.combox_Buckets.Text;
124 | progress_Upload.Value = 0;
125 | folder = this.tbox_Folder.Text;
126 | });
127 |
128 |
129 |
130 | for (globalIndex = 0; globalIndex < uploadList.Count; globalIndex++)
131 | {
132 | if(!string.IsNullOrEmpty(folder))
133 | ossHelper.PutFile(uploadList[globalIndex].FilePath, folder + "/" + uploadList[globalIndex].FileName);
134 | else
135 | ossHelper.PutFile(uploadList[globalIndex].FilePath, uploadList[globalIndex].FileName);
136 |
137 | Dispatcher.Invoke(() => {
138 | if (remain == 0)
139 | {
140 | progress_Upload.Value += step;
141 | }
142 | else
143 | {
144 | if ( globalIndex == ( uploadList.Count - 1))
145 | {
146 | progress_Upload.Value += step + remain;
147 | }
148 | else
149 | {
150 | progress_Upload.Value += step;
151 | }
152 | }
153 | });
154 | }
155 | }
156 |
157 | private void btn_ConfirmAccessKey_Click(object sender, RoutedEventArgs e)
158 | {
159 | Key = this.tbox_Key.Text.Trim();
160 | Secret = this.tbox_Secret.Text.Trim();
161 | EndPoint = this.combox_EndPoint.Text.Substring(5);
162 |
163 | if(this.combox_EndPoint.SelectedIndex == -1)
164 | {
165 | MessageBox.Show("请选择EndPoint");
166 | return;
167 | }
168 |
169 | ossHelper = new ZtiLib.OssHelper(Key,Secret,EndPoint,"",false);
170 | IEnumerable bucketList = ossHelper.ListBuckets();
171 | this.combox_Buckets.ItemsSource = bucketList.Select(x => x.Name);
172 | this.combox_DownloadBuckets.ItemsSource = bucketList.Select(x => x.Name);
173 | BucketName = bucketList.ElementAt(0).Name;
174 | ossHelper.BucketName = BucketName;
175 | MessageBox.Show("配置成功");
176 | }
177 |
178 | private List EndPointList()
179 | {
180 | List list = new List();
181 | list.Add("华东 1-http://oss-cn-hangzhou.aliyuncs.com");
182 | list.Add("华东 2-http://oss-cn-shanghai-internal.aliyuncs.com");
183 | return list;
184 | }
185 |
186 | private void listview_Upload_SelectionChanged(object sender, SelectionChangedEventArgs e)
187 | {
188 | int index = this.listview_Upload.SelectedIndex;
189 | if(index != -1)
190 | {
191 | if(uploadList[index].FileType == ".jpg" || uploadList[index].FileType == ".bmp" || uploadList[index].FileType == ".png")
192 | this.image_Preview.Source = new BitmapImage(new Uri(uploadList[index].FilePath));
193 | }
194 | }
195 |
196 | private void combox_DownloadBuckets_SelectionChanged(object sender, SelectionChangedEventArgs e)
197 | {
198 | if(this.combox_DownloadBuckets.SelectedIndex != -1)
199 | {
200 | DownloadBucketName = this.combox_DownloadBuckets.SelectedItem.ToString();
201 | ossHelper.BucketName = DownloadBucketName;
202 | }
203 | }
204 |
205 | private void btn_ListFile_Click(object sender, RoutedEventArgs e)
206 | {
207 | if (string.IsNullOrEmpty(Key) || string.IsNullOrEmpty(Secret))
208 | {
209 | MessageBox.Show("请先配置访问密钥");
210 | this.tab.SelectedIndex = 2;
211 | return;
212 | }
213 |
214 | if(string.IsNullOrEmpty(DownloadBucketName))
215 | {
216 | MessageBox.Show("请选择Bucket");
217 | return;
218 | }
219 |
220 | IEnumerable fileList = ossHelper.ListObjects();
221 |
222 | var result = fileList.Select(x => new ObjectInfo{
223 | IsCheck = false,
224 | FileName = x.Key,
225 | FileSize = (x.Size / 1024).ToString() + "KB"
226 | });
227 | foreach (var item in result)
228 | {
229 | downloadList.Add(item);
230 | }
231 | this.listview_Download.ItemsSource = downloadList;
232 | }
233 |
234 | private void btn_Download_Click(object sender, RoutedEventArgs e)
235 | {
236 |
237 | }
238 |
239 | private void cbox_CheckAll_Checked(object sender, RoutedEventArgs e)
240 | {
241 | if (cbox_CheckAll.IsChecked.Value == true)
242 | downloadList.ToList().ForEach(x => x.IsCheck = true);
243 | else
244 | downloadList.ToList().ForEach(x => x.IsCheck = false);
245 |
246 | this.listview_Download.ItemsSource = null;
247 | this.listview_Download.ItemsSource = downloadList;
248 | }
249 |
250 | private void btn_BrowseDownloadFolder_Click(object sender, RoutedEventArgs e)
251 | {
252 | System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
253 | if(dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
254 | {
255 | this.tbox_DownloadFolder.Text = dialog.SelectedPath;
256 | }
257 | }
258 | }
259 | }
260 |
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/ObjectInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace OssDemo
8 | {
9 | class ObjectInfo
10 | {
11 | public bool IsCheck { get; set; }
12 | public string FileName { get; set; }
13 |
14 | public string FilePath { get; set; }
15 |
16 | public string FileType { get; set; }
17 |
18 | public string FileSize { get; set; }
19 |
20 | ///
21 | /// Progress(Reserverd)
22 | ///
23 | public string Progress { get; set; }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/OssDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {9E6E68D3-EE34-451E-A0AB-A70CB01A38F2}
8 | WinExe
9 | Properties
10 | OssDemo
11 | OssDemo
12 | v4.5
13 | 512
14 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
15 | 4
16 |
17 |
18 | AnyCPU
19 | true
20 | full
21 | false
22 | bin\Debug\
23 | DEBUG;TRACE
24 | prompt
25 | 4
26 |
27 |
28 | AnyCPU
29 | pdbonly
30 | true
31 | bin\Release\
32 | TRACE
33 | prompt
34 | 4
35 |
36 |
37 |
38 | ..\packages\Aliyun.OSS.SDK.2.8.0\lib\Aliyun.OSS.dll
39 | True
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | 4.0
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | MSBuild:Compile
59 | Designer
60 |
61 |
62 | MSBuild:Compile
63 | Designer
64 |
65 |
66 | App.xaml
67 | Code
68 |
69 |
70 | MainWindow.xaml
71 | Code
72 |
73 |
74 |
75 |
76 |
77 | Code
78 |
79 |
80 | True
81 | True
82 | Resources.resx
83 |
84 |
85 | True
86 | Settings.settings
87 | True
88 |
89 |
90 | ResXFileCodeGenerator
91 | Resources.Designer.cs
92 |
93 |
94 |
95 | SettingsSingleFileGenerator
96 | Settings.Designer.cs
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 | {168931ba-558b-41e3-9030-70e9ab44d21b}
106 | AliyunOssHelperLib
107 |
108 |
109 |
110 |
117 |
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Resources;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.InteropServices;
5 | using System.Windows;
6 |
7 | // General Information about an assembly is controlled through the following
8 | // set of attributes. Change these attribute values to modify the information
9 | // associated with an assembly.
10 | [assembly: AssemblyTitle("OssDemo")]
11 | [assembly: AssemblyDescription("")]
12 | [assembly: AssemblyConfiguration("")]
13 | [assembly: AssemblyCompany("")]
14 | [assembly: AssemblyProduct("OssDemo")]
15 | [assembly: AssemblyCopyright("Copyright © 2018")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 |
19 | // Setting ComVisible to false makes the types in this assembly not visible
20 | // to COM components. If you need to access a type in this assembly from
21 | // COM, set the ComVisible attribute to true on that type.
22 | [assembly: ComVisible(false)]
23 |
24 | //In order to begin building localizable applications, set
25 | //CultureYouAreCodingWith in your .csproj file
26 | //inside a . For example, if you are using US english
27 | //in your source files, set the to en-US. Then uncomment
28 | //the NeutralResourceLanguage attribute below. Update the "en-US" in
29 | //the line below to match the UICulture setting in the project file.
30 |
31 | //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
32 |
33 |
34 | [assembly: ThemeInfo(
35 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
36 | //(used if a resource is not found in the page,
37 | // or application resource dictionaries)
38 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
39 | //(used if a resource is not found in the page,
40 | // app, or any theme specific resource dictionaries)
41 | )]
42 |
43 |
44 | // Version information for an assembly consists of the following four values:
45 | //
46 | // Major Version
47 | // Minor Version
48 | // Build Number
49 | // Revision
50 | //
51 | // You can specify all the values or you can default the Build and Revision Numbers
52 | // by using the '*' as shown below:
53 | // [assembly: AssemblyVersion("1.0.*")]
54 | [assembly: AssemblyVersion("1.0.0.0")]
55 | [assembly: AssemblyFileVersion("1.0.0.0")]
56 |
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace OssDemo.Properties
12 | {
13 |
14 |
15 | ///
16 | /// A strongly-typed resource class, for looking up localized strings, etc.
17 | ///
18 | // This class was auto-generated by the StronglyTypedResourceBuilder
19 | // class via a tool like ResGen or Visual Studio.
20 | // To add or remove a member, edit your .ResX file then rerun ResGen
21 | // with the /str option, or rebuild your VS project.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources
26 | {
27 |
28 | private static global::System.Resources.ResourceManager resourceMan;
29 |
30 | private static global::System.Globalization.CultureInfo resourceCulture;
31 |
32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
33 | internal Resources()
34 | {
35 | }
36 |
37 | ///
38 | /// Returns the cached ResourceManager instance used by this class.
39 | ///
40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
41 | internal static global::System.Resources.ResourceManager ResourceManager
42 | {
43 | get
44 | {
45 | if ((resourceMan == null))
46 | {
47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("OssDemo.Properties.Resources", typeof(Resources).Assembly);
48 | resourceMan = temp;
49 | }
50 | return resourceMan;
51 | }
52 | }
53 |
54 | ///
55 | /// Overrides the current thread's CurrentUICulture property for all
56 | /// resource lookups using this strongly typed resource class.
57 | ///
58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
59 | internal static global::System.Globalization.CultureInfo Culture
60 | {
61 | get
62 | {
63 | return resourceCulture;
64 | }
65 | set
66 | {
67 | resourceCulture = value;
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace OssDemo.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/ScreenShots/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhaotianff/aliyun-oss-csharp-Helper/387313672882353814fa31f396bb80f6d52a91b3/AliyunOssHelperLib/OssDemo/ScreenShots/1.png
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/ScreenShots/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhaotianff/aliyun-oss-csharp-Helper/387313672882353814fa31f396bb80f6d52a91b3/AliyunOssHelperLib/OssDemo/ScreenShots/2.png
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/ScreenShots/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhaotianff/aliyun-oss-csharp-Helper/387313672882353814fa31f396bb80f6d52a91b3/AliyunOssHelperLib/OssDemo/ScreenShots/3.png
--------------------------------------------------------------------------------
/AliyunOssHelperLib/OssDemo/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Aliyun-Oss-CSharp-Helper
2 |
3 | 阿里云 OSS .Net SDK 再次封装
4 |
5 | 这里的再次封装主要是为了使用方便,官方给的文档太分散。
6 |
7 | 函数列表
8 | bool CreateBucket()
9 | 创建Bucket 返回:true-创建成功 false-创建失败
10 | CannedAccessControlList GetBucketAcl()
11 | 获取Bucket访问权限 返回:CannedAccessControlList枚举类型
12 | IEnumerable ListBuckets()
13 | 列出用户所有Bucket 返回:IEnumerable<Bucket>
14 | bool IsBucketExist()
15 | 判断Bucket是否存在
16 | bool IsBucketExist(string bucketName)
17 | 判断指定的Bucket是否存在 参数:bucketName-指定Bucket 返回:true-存在 false-不存在
18 | bool SetBucketAcl(CannedAccessControlList accessType)
19 | 设置Bucket访问权限 参数:accessType-访问权限 返回:true-设置成功 false-设置失败
20 | bool SetBucketAcl()
21 | 设置指定Bucket访问权限 参数:bucketName-指定Bucket accessType-访问权限 返回:true-设置成功 false-设置失败
22 | bool DeleteBucket()
23 | 删除Bucket 返回:true-删除成功 false-删除失败
24 | bool DeleteBucket(string bucketName)
25 | 删除指定Bucket
26 | ==============================================================
27 | bool PutString(string str,string name)
28 | 上传字符串 返回:true-上传成功 false-上传失败 参数:str-字符串 name-在OSS存储用的标识(必须唯一,否则会替换)
29 | bool PutString(string bucketName,string str,string name)
30 | 上传字符串 返回:true-上传成功 false-上传失败 参数:bucketName-Bucket名字 str-字符串 name-在OSS存储用的标识
31 | bool PutFile(string filePath)
32 | 上传文件 返回:true-上传成功 false-上传失败 参数:filePath-要上传的文件路径
33 | bool PutFile(string filePath,string objectKey)
34 | 上传文件 返回:true-上传成功 false-上传失败 参数:filePath-要上传的文件路径 objectKey-在OSS中存储用的标识
35 | bool PutFile(string bucketName,string filePath,string objectKey)
36 | 上传文件 返回:true-上传成功 false-上传失败 参数:bucketName-指定Bucket filePath-要上传的文件路径 objectKey-在OSS中存储用的标识
37 | bool PutFile(string filePath,string objectKey,EventHandler progressCallback)
38 | 上传文件并显示进度 返回:true-上传成功 false-上传失败 参数:filePath-要上传的文件路径 objectKey-在OSS中存储用的标识 progressCallback-上传进度处理函数,可参考下面的代码
39 | 上传进度事件处理函数
40 |
41 | private static void streamProgressCallback(object sender, StreamTransferProgressArgs args)
42 | {
43 | System.Console.WriteLine("ProgressCallback - TotalBytes:{0}, TransferredBytes:{1}",
44 | args.TotalBytes, args.TransferredBytes);
45 | }
46 |
47 | bool PutFile(string bucketName,string filePath,string objectKey,EventHandler progressCallback)
48 | 上传文件并显示进度 返回:true-上传成功 false-上传失败 参数:bucketName-指定Bucket filePath-要上传的文件路径 objectKey-在OSS中存储用的标识 progressCallback-上传进度处理函数
49 | 使用示例
50 | 示例程序
51 | 提供简单的上传,下载和管理功能。示例程序只用到一些基本的函数,掌握这些基本函数,我们就已经掌握了OSS的基本使用了。如果后面有时间,会把大部分函数都用到示例程序中去。
52 |
53 | 软件截图
54 |
55 |
56 |
上传
57 |
58 |
59 |
60 |
下载
61 |
62 |
63 |
64 |
配置
65 |
66 |
--------------------------------------------------------------------------------