C#新手.
我正在try 编写一些代码,它将从一个AWS帐户复制S3存储桶内容,并使用AWS SDK将它们放入另一个S3帐户.
我的问题是,虽然文件名出现在目标存储桶中,但内容/文件似乎已损坏. 作为测试,我让它复制并移动了一个图像. 源映像是193KB,但目标存储桶中的文件是339KB,这似乎有点小.
以下是我的代码.
以ListAndCopyObjects
方法作为入口点开始.
客户端,已在代码的另一部分中定义了目标客户端.
如有任何帮助,我们不胜感激.
我已经在这个问题上苦苦思索好几天了.
public static async Task ListAndCopyObjects(string bucketName, string folderName, AmazonS3Client client)
{
// Read all bucket files
Console.WriteLine("Listing Objects");
var listObjects = client.Paginators.ListObjectsV2(new ListObjectsV2Request()
{
BucketName = bucketName,
Prefix = folderName,
StartAfter = folderName
});
Console.WriteLine("Loop through Files");
await foreach (var response in listObjects.Responses)
{
Console.WriteLine($"HttpStatusCode: {response.HttpStatusCode}");
Console.WriteLine($"Number of Keys: {response.KeyCount}");
foreach (var entry in response.S3Objects)
{
Console.WriteLine($"Key = {entry.Key} Size = {entry.Size}");
//Download file data
NameValueCollection fileContent = await DownloadObject(client, bucketName, entry.Key);
Console.WriteLine(fileContent);
//Upload file
await UploadObject(destinationClient, Environment.GetEnvironmentVariable("DESTINATION_BUCKET"),
entry.Key, fileContent);
}
}
}
private static async Task<bool> UploadObject(AmazonS3Client client, string bucketName, string objectName,
NameValueCollection fileContents)
{
var request = new PutObjectRequest
{
BucketName = bucketName,
Key = objectName,
ContentBody = fileContents["content"],
ContentType = fileContents["contentType"]
};
var response = await client.PutObjectAsync(request);
if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
Console.WriteLine($"Successfully uploaded {objectName} to {bucketName}.");
return true;
}
else
{
Console.WriteLine($"Could not upload {objectName} to {bucketName}.");
return false;
}
}
private static async Task<NameValueCollection> DownloadObject(AmazonS3Client client, string bucketName, string objectName)
{
Console.WriteLine("Downloading File");
NameValueCollection fileData = new NameValueCollection();
try
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = bucketName,
Key = objectName
};
using (GetObjectResponse response = await client.GetObjectAsync(request))
using (Stream responseStream = response.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
{
string title = response.Metadata["x-amz-meta-title"];
string contentType = response.Headers["Content-Type"];
Console.WriteLine("Object metadata, Title: {0}", title);
Console.WriteLine("Content type: {0}", contentType);
fileData["contentType"] = contentType;
fileData["content"] = reader.ReadToEnd();
return fileData;
}
}
catch (AmazonS3Exception e)
{
Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message);
}
catch (Exception e)
{
Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
}
return fileData;
}