Organize Code

master
ZGGSONG 3 years ago
parent 504a0bb5c2
commit cf2402073f

@ -1,85 +0,0 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace S3Demo
{
using System;
using System.IO;
using System.Threading.Tasks;
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
/// <summary>
/// This example shows how to use the Amazon Simple Storage System
/// (Amazon S3) client to copy an object from an Amazon S3 bucket to
/// another location such as your local system. The code uses the AWS
/// SDK for .NET version 3.7 and .NET Core 5.0.
/// </summary>
class GetObject
{
public static async Task Readobjectdata(string bucketName, string keyName, BasicAWSCredentials credentials, AmazonS3Config conf)
{
//const string bucketName = "doc-example-bucket";
//const string keyName = "filetodownload";
// If the Amazon Region where the S3 bucket was created is not
// the same as the region defined for the default user, specify
// the region as a parameter to the client constructor.
// For example: RegionEndpoint.USWest2;
IAmazonS3 client = new AmazonS3Client(credentials, conf);
await ReadObjectDataAsync(client, bucketName, keyName);
}
/// <summary>
/// This method copies the contents of the object keyName to another
/// location, for example, to your local system.
/// </summary>
/// <param name="client">The initialize S3 client used to call
/// GetObjectAsync.</param>
/// <param name="bucketName">The name of the S3 bucket which contains
/// the object to copy.</param>
/// <param name="keyName">The name of the object you want to copy.</param>
static async Task ReadObjectDataAsync(IAmazonS3 client, string bucketName, string keyName)
{
string responseBody = string.Empty;
try
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = bucketName,
Key = keyName,
};
using (GetObjectResponse response = await client.GetObjectAsync(request))
using (Stream responseStream = response.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
{
// Assume you have "title" as medata added to the object.
string title = response.Metadata["x-amz-meta-title"];
string contentType = response.Headers["Content-Type"];
int tag = response.TagCount;
foreach (var item in response.Key)
{
Console.WriteLine($"Object tag: {item}");
}
Console.WriteLine($"Object metadata, Title: {title}");
Console.WriteLine($"Content type: {contentType}");
// Retrieve the contents of the file.
responseBody = reader.ReadToEnd();
// Write the contents of the file to disk.
string filePath = $"C:\\Temp\\copy_of_{keyName}";
}
}
catch (AmazonS3Exception e)
{
// If the bucket or the object do not exist
Console.WriteLine($"Error: '{e.Message}'");
}
}
}
}

@ -0,0 +1,46 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace S3Demo.Model
{
// This example uses the AWS SDK for .NET to check isExist the Amazon Simple Storage
// Service (Amazon S3) buckets belonging to the default account. This code
// was written using AWS SDK for .NET v3.5 and .NET Core 5.0.
class BucketModel
{
private static IAmazonS3 _s3Client;
/// <summary>
/// 判断存储桶是否存在
/// </summary>
/// <param name="bucketName"></param>
/// <param name="credentials"></param>
/// <param name="conf"></param>
/// <returns></returns>
public static async Task<bool> isExistBucket(string bucketName, BasicAWSCredentials credentials, AmazonS3Config conf)
{
bool flag = false;
_s3Client = new AmazonS3Client(credentials, conf);
var response = await _s3Client.ListBucketsAsync();
List<S3Bucket> bucketList = response.Buckets;
bucketList.ForEach(b => Console.WriteLine($"Bucket name: {b.BucketName}, created on: {b.CreationDate}"));
foreach (var item in bucketList)
{
if (item.BucketName == bucketName)
{
flag = true;
}
}
return flag;
}
}
}

@ -1,23 +1,20 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 // SPDX - License - Identifier: Apache - 2.0
namespace S3Demo using System;
{ using System.Collections.Generic;
using System; using System.IO;
using System.Collections.Generic; using System.Threading.Tasks;
using System.Threading.Tasks; using Amazon;
using Amazon; using Amazon.Runtime;
using Amazon.Runtime; using Amazon.S3;
using Amazon.S3; using Amazon.S3.Model;
using Amazon.S3.Model;
/// <summary> namespace S3Demo.Model
/// This example shows how to work with tags in Amazon Simple Storage {
/// System (Amazon S3) objects. The example was created using the AWS SDK class ObjectModel
/// for .NET version 3.7 and .NET Core 5.0.
/// </summary>
public class ObjectTag
{ {
#region 发送对象(带标签)
public static async Task Putobjectswithtags(string bucketName, string keyName, string filePath, string[] tags, BasicAWSCredentials credentials, AmazonS3Config conf) public static async Task Putobjectswithtags(string bucketName, string keyName, string filePath, string[] tags, BasicAWSCredentials credentials, AmazonS3Config conf)
{ {
//string bucketName = "doc-example-bucket"; //string bucketName = "doc-example-bucket";
@ -112,5 +109,77 @@ namespace S3Demo
$"Error: '{ex.Message}'"); $"Error: '{ex.Message}'");
} }
} }
#endregion
#region 查找对象
public static async Task Readobjectdata(string bucketName, string keyName, BasicAWSCredentials credentials, AmazonS3Config conf)
{
//const string bucketName = "doc-example-bucket";
//const string keyName = "filetodownload";
// If the Amazon Region where the S3 bucket was created is not
// the same as the region defined for the default user, specify
// the region as a parameter to the client constructor.
// For example: RegionEndpoint.USWest2;
IAmazonS3 client = new AmazonS3Client(credentials, conf);
await ReadObjectDataAsync(client, bucketName, keyName);
}
/// <summary>
/// This method copies the contents of the object keyName to another
/// location, for example, to your local system.
/// </summary>
/// <param name="client">The initialize S3 client used to call
/// GetObjectAsync.</param>
/// <param name="bucketName">The name of the S3 bucket which contains
/// the object to copy.</param>
/// <param name="keyName">The name of the object you want to copy.</param>
static async Task ReadObjectDataAsync(IAmazonS3 client, string bucketName, string keyName)
{
string responseBody = string.Empty;
try
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = bucketName,
Key = keyName,
};
// Get tag
GetObjectTaggingRequest getTagsRequest = new()
{
BucketName = bucketName,
Key = keyName,
};
GetObjectTaggingResponse objectTags = await client.GetObjectTaggingAsync(getTagsRequest);
// Display the tag values.
objectTags.Tagging
.ForEach(t => Console.WriteLine($"Key: {t.Key}, Value: {t.Value}"));
using (GetObjectResponse response = await client.GetObjectAsync(request))
using (Stream responseStream = response.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
{
// Assume you have "title" as medata added to the object.
string title = response.Metadata["x-amz-meta-title"];
string contentType = response.Headers["Content-Type"];
Console.WriteLine($"Object keyName: {response.Key}");
Console.WriteLine($"Object metadata, Title: {title}");
Console.WriteLine($"Content type: {contentType}");
// Retrieve the contents of the file.
responseBody = reader.ReadToEnd();
// Write the contents of the file to disk.
string filePath = $"C:\\Temp\\copy_of_{keyName}";
}
}
catch (AmazonS3Exception e)
{
// If the bucket or the object do not exist
Console.WriteLine($"Error: '{e.Message}'");
}
}
#endregion
} }
} }

@ -2,6 +2,8 @@
using Amazon.Runtime; using Amazon.Runtime;
using Amazon.S3; using Amazon.S3;
using System; using System;
using S3Demo.Stack;
using S3Demo.Model;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace S3Demo namespace S3Demo
@ -27,22 +29,38 @@ namespace S3Demo
{ {
try try
{ {
//uploaddir //upload Dir
string dirPath = @"C:\Users\song\Pictures\Saved Pictures\"; string dirPath = @"C:\Users\song\Pictures\Saved Pictures\";
string suffix = "*.png"; string suffix = "*.png";
//await UploadDirMPUHighLevelAPI.Uploaderdir(bucketName, dirPath, suffix, credentials, conf); //await UploadDirMPUHighLevelAPI.Uploaderdir(bucketName, dirPath, suffix, credentials, conf);
//uploadfile //upload File
string keyName = "360.png"; string keyName = "logo.png";
//await UploadFileMPUHighLevelAPI.Uploaderfile(bucketName, keyName, dirPath, credentials, conf); //await UploadFileMPUHighLevelAPI.Uploaderfile(bucketName, keyName, dirPath, credentials, conf);
//objectTag //list Objects
//await ListObjects.Listingobjects(bucketName, credentials, conf);
//upload Object With Tag
string filaPath = @"C:\Users\song\Pictures\Saved Pictures\" + keyName; string filaPath = @"C:\Users\song\Pictures\Saved Pictures\" + keyName;
String[] tags = new String[] { "SN123456", DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:sszzz"), "AB023" }; String[] tags = new String[] { "SN123456", DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:sszzz"), "AB023" };
await ObjectTag.Putobjectswithtags(bucketName, keyName, filaPath, tags, credentials, conf); //await ObjectModel.Putobjectswithtags(bucketName, keyName, filaPath, tags, credentials, conf);
//read Object
await ObjectModel.Readobjectdata(bucketName, keyName, credentials, conf);
//getObject //isExist Bucket
//await GetObject.Readobjectdata(bucketName, keyName, credentials, conf); //从"minio/test"中取出存储桶名
var _bucketName = bucketName.Split('/')[1];
var flag = await BucketModel.isExistBucket(_bucketName, credentials, conf);
if (flag)
{
Console.WriteLine("exist");
}
else
{
Console.WriteLine("not exist");
}
} }
catch (Exception ex) catch (Exception ex)
{ {

@ -51,12 +51,13 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="GetObject.cs" /> <Compile Include="Model\BucketModel.cs" />
<Compile Include="ObjectTag.cs" /> <Compile Include="Model\ObjectModel.cs" />
<Compile Include="Stack\ListObjects.cs" />
<Compile Include="Run.cs" /> <Compile Include="Run.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UploadDirMPUHighLevelAPI.cs" /> <Compile Include="Stack\UploadDirMPUHighLevelAPI.cs" />
<Compile Include="UploadFileMPUHighLevelAPI.cs" /> <Compile Include="Stack\UploadFileMPUHighLevelAPI.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="App.config" /> <None Include="App.config" />

@ -0,0 +1,72 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/// <summary>
/// List the objects in an Amazon Simple Storage Service (Amazon S3) bucket.
/// The example was created using the AWS SDK for .NET version 3.7 and
/// .NET Core 5.0.
/// </summary>
namespace S3Demo.Stack
{
// snippet-start:[S3.dotNET.ListObjectsExample]
using System;
using System.Threading.Tasks;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
public class ListObjects
{
public static async Task Listingobjects(string bucketName, BasicAWSCredentials credentials, AmazonS3Config conf)
{
//string bucketName = "doc-example-bucket";
IAmazonS3 client;
using (client = new AmazonS3Client(credentials, conf))
{
Console.WriteLine($"Listing objects stored in the bucket {bucketName}.");
await ListingObjectsAsync(client, bucketName);
}
}
/// <summary>
/// Uses the client object to get a list of the objects in the Amazon
/// S3 bucket in the bucketName parameter.
/// </summary>
/// <param name="client">The initialized S3 client obect used to call
/// the ListObjectsAsync method.</param>
/// <param name="bucketName">The bucket name for which you want to
/// retrieve a list of objects.</param>
public static async Task ListingObjectsAsync(IAmazonS3 client, string bucketName)
{
try
{
ListObjectsV2Request request = new()
{
BucketName = bucketName,
MaxKeys = 5,
};
var response = new ListObjectsV2Response();
do
{
response = await client.ListObjectsV2Async(request);
response.S3Objects
.ForEach(obj => Console.WriteLine($"{obj.Key,-35}{obj.LastModified.ToShortDateString(),10}{obj.Size,10}"));
// If the response is truncated, set the request ContinuationToken
// from the NextContinuationToken property of the response.
request.ContinuationToken = response.NextContinuationToken;
} while (response.IsTruncated);
}
catch (AmazonS3Exception ex)
{
Console.WriteLine($"Error encountered on server. Message:'{ex.Message}' getting list of objects.");
}
}
}
// snippet-end:[S3.dotNET.ListObjectsExample]
}

@ -7,7 +7,7 @@ using Amazon.Runtime;
using Amazon.S3; using Amazon.S3;
using Amazon.S3.Transfer; using Amazon.S3.Transfer;
namespace S3Demo namespace S3Demo.Stack
{ {
/// <summary> /// <summary>
/// This example uses the Amazon Simple Storage Service (Amazon S3) /// This example uses the Amazon Simple Storage Service (Amazon S3)

@ -7,7 +7,7 @@ using Amazon.Runtime;
using Amazon.S3; using Amazon.S3;
using Amazon.S3.Transfer; using Amazon.S3.Transfer;
namespace S3Demo namespace S3Demo.Stack
{ {
/// <summary> /// <summary>
/// This example shows how to use the TransferUtility api for Amazon Simple /// This example shows how to use the TransferUtility api for Amazon Simple
Loading…
Cancel
Save