· 8 years ago · Nov 16, 2017, 12:42 AM
1public class clsAwsS3
2{
3 string accessKey { get; set; }
4 string secretKey { get; set; }
5 string bucket { get; set; }
6 RegionEndpoint region { get; set; }
7 IAmazonS3 client;
8
9 public clsAwsS3(string strBucket, string strAccessKey, string strSecretKey, RegionEndpoint region)
10 {
11 this.bucket = strBucket;
12 this.accessKey = strAccessKey;
13 this.secretKey = strSecretKey;
14 this.region = region;
15 login();
16 }
17
18 private void login()
19 {
20 client = new AmazonS3Client(accessKey, secretKey, region);
21 }
22
23 public List<string> getItems(string strPrefix = "")
24 {
25 List<string> lstResult = new List<string>();
26 ListObjectsV2Request listRequest;
27
28 if (strPrefix == "")
29 listRequest = new ListObjectsV2Request
30 {
31 BucketName = bucket
32 };
33 else
34 listRequest = new ListObjectsV2Request
35 {
36 BucketName = bucket,
37 Prefix = strPrefix
38 };
39
40 ListObjectsV2Response listResponse;
41
42 do
43 {
44 listResponse = client.ListObjectsV2(listRequest);
45
46 foreach (S3Object awsObject in listResponse.S3Objects)
47 lstResult.Add(awsObject.Key);
48
49 listRequest.ContinuationToken = listResponse.NextContinuationToken;
50 } while (listResponse.IsTruncated);
51
52 return lstResult;
53 }
54
55 public string downloadItem(string strItemKey, string strDestination)
56 {
57 GetObjectRequest request = new GetObjectRequest
58 {
59 BucketName = bucket,
60 Key = strItemKey
61 };
62
63 using (GetObjectResponse response = client.GetObject(request))
64 {
65 response.WriteResponseStreamToFile(strDestination);
66 }
67
68 return strDestination;
69 }
70
71 public void copyItem(string strItemKeySource, string strItemKeyDestination)
72 {
73 CopyObjectRequest copyRequest = new CopyObjectRequest
74 {
75 SourceBucket = bucket,
76 SourceKey = strItemKeySource,
77 DestinationBucket = bucket,
78 DestinationKey = strItemKeyDestination
79 };
80
81 CopyObjectResponse copyResponse = client.CopyObject(copyRequest);
82
83 if (copyResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
84 throw new Exception("Item has an error");
85 }
86
87 public void deleteItem(string strItemKey)
88 {
89 DeleteObjectRequest deleteObject = new DeleteObjectRequest
90 {
91 BucketName = bucket,
92 Key = strItemKey
93 };
94
95 DeleteObjectResponse deleteResponse = client.DeleteObject(deleteObject);
96 }
97}