gpt4 book ai didi

c# - 将文件从 amazon s3 帐户传输到另一个

转载 作者:行者123 更新时间:2023-11-30 12:11:06 25 4
gpt4 key购买 nike

我正在编写一个应用程序,我们需要在不同的 s3 帐户之间传输文件,我们不想在上传到目标 s3 帐户之前将文件保存在本地。
所以我们使用这个获取源文件流:

public Stream GetFileStream(string path)
{
var pathPieces = path.Split('/');
string bucket = pathPieces[0];
string fileName = pathPieces[pathPieces.Length - 1];

GetObjectRequest request = new GetObjectRequest();
request.BucketName = bucket;
request.Key = fileName;

GetObjectResponse response = Client.GetObject(request);

return response.ResponseStream;
}

然后我们使用这个流上传到目的地:

    TransferUtility transferUtility = new TransferUtility(Client);
transferUtility.S3Client.PutBucket(new PutBucketRequest() { UseClientRegion = true }.WithBucketName(bucket));
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest()
.WithBucketName(bucket)
.WithKey(key)
.WithPartSize(1024)
.WithTimeout(100 * 60 * 60 * 1000)
.WithAutoCloseStream(true)
.WithCannedACL(S3CannedACL.PublicReadWrite)
.WithInputStream(fileStream) as TransferUtilityUploadRequest;

transferUtility.Upload(request);

但是在最后一行“上传”函数调用中我总是得到这个错误:此流不支持搜索操作。

有没有不同的方法来做我想做的事情?因为它的接缝方式不正确

最佳答案

我遇到了这个问题,并发布了我用来解决它的方法。从 Jon Skeet 那里借用了一些代码。它对我有用,但我知道它有点笨拙,可能可以改进。

string filename = "nameoffiletocopy"

using (Stream stream = GetS3Stream(filename))
{
AmazonS3Config config = new AmazonS3Config
{CommunicationProtocol = Protocol.HTTP};
AmazonS3 client =
AWSClientFactory.CreateAmazonS3Client(
"destinationaccesskey",
"destinationsecretacceskey",
config);
string destinationBucketName = "destinationbucketname";

PutObjectRequest request = new PutObjectRequest
{
BucketName = destinationBucketName,
InputStream = stream,
Key = filename,
CannedACL = S3CannedACL.PublicRead
};

PutObjectResponse response = client.PutObject(request);
}

private static Stream GetS3Stream(string filename)
{
AmazonS3Config config = new AmazonS3Config
{CommunicationProtocol = Protocol.HTTP};
AmazonS3 client = AWSClientFactory.CreateAmazonS3Client(
"sourceaccesskey",
"sourcesecretacceskey",
config);
string sourceBucketName = "sourcebucketname";

GetObjectRequest request = new GetObjectRequest
{
BucketName = sourceBucketName,
Key = filename
};

using (GetObjectResponse response = client.GetObject(request))
{
byte[] binaryData =
ReadFully(response.ResponseStream, -1);
//ReadyFully from Jon Skeet's blog
return new MemoryStream(binaryData);
}
}

ReadFully 方法由 Jon Skeet 完整解释

关于c# - 将文件从 amazon s3 帐户传输到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16095368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com