c#写文件到S3,然后删除本地文件
c# Write file to S3 and then delete the local file
以下程序从 Web 服务中提取数据并将其写入 csv,将文件上传到 S3,然后将其删除。我遇到的问题是它无法删除文件,因为它说 "System.IO.IOException: 'The process cannot access the file 'file.csv' because it is being used by another process.",我猜它还没有完成对 S3 的写入,因为它没有显示在那里。有什么建议吗?
这里我关闭文件,上传到S3,然后尝试删除。
outputFile.Flush();
outputFile.Close();
AmazonS3Uploader awsfu = new AmazonS3Uploader();
awsfu.UploadFile(outputfilePath, "api-end-point", filenameaws);
System.IO.File.Delete(@outputfilePath);
以下是S3上传的代码
class AmazonS3Uploader
{
public void UploadFile(string filePath, string bucketName, string keyName)
{
var client1 = new AmazonS3Client(Amazon.RegionEndpoint.USEast2);
Console.WriteLine("s3 writing");
try
{
PutObjectRequest Request = new PutObjectRequest
{
BucketName = bucketName,
Key = keyName,
FilePath = filePath,
};
client1.PutObjectAsync(Request);
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
throw new Exception("Check the provided AWS Credentials.");
}
else
{
throw new Exception("Error occurred: " + amazonS3Exception.Message);
}
}
//System.IO.File.Delete(@filePath); edit
}
}
您正在调用一个异步方法,而不是等待它完成。
正如 documentation 所说:
[PutObjectAsync] initiates the asynchronous execution of the PutObject operation.
因为您没有等待该方法完成,所以代码会继续并尝试在文件仍在上传时删除文件(两次!)。
解决此问题的最简单方法是更改代码以使用 synchronous version:
client1.PutObject(Request);
以下程序从 Web 服务中提取数据并将其写入 csv,将文件上传到 S3,然后将其删除。我遇到的问题是它无法删除文件,因为它说 "System.IO.IOException: 'The process cannot access the file 'file.csv' because it is being used by another process.",我猜它还没有完成对 S3 的写入,因为它没有显示在那里。有什么建议吗?
这里我关闭文件,上传到S3,然后尝试删除。
outputFile.Flush();
outputFile.Close();
AmazonS3Uploader awsfu = new AmazonS3Uploader();
awsfu.UploadFile(outputfilePath, "api-end-point", filenameaws);
System.IO.File.Delete(@outputfilePath);
以下是S3上传的代码
class AmazonS3Uploader
{
public void UploadFile(string filePath, string bucketName, string keyName)
{
var client1 = new AmazonS3Client(Amazon.RegionEndpoint.USEast2);
Console.WriteLine("s3 writing");
try
{
PutObjectRequest Request = new PutObjectRequest
{
BucketName = bucketName,
Key = keyName,
FilePath = filePath,
};
client1.PutObjectAsync(Request);
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
throw new Exception("Check the provided AWS Credentials.");
}
else
{
throw new Exception("Error occurred: " + amazonS3Exception.Message);
}
}
//System.IO.File.Delete(@filePath); edit
}
}
您正在调用一个异步方法,而不是等待它完成。
正如 documentation 所说:
[PutObjectAsync] initiates the asynchronous execution of the PutObject operation.
因为您没有等待该方法完成,所以代码会继续并尝试在文件仍在上传时删除文件(两次!)。
解决此问题的最简单方法是更改代码以使用 synchronous version:
client1.PutObject(Request);