以下程序从Web服务中提取数据将其写入csv,将文件上载到S3然后将其删除。我遇到的问题是它无法删除文件,因为它说“System.IO.IOException:'进程无法访问文件'file.csv',因为它正被另一个进程使用。”,我猜它还没有完成写入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
}
}
答案 0 :(得分:1)
您正在调用异步方法而不是等待它完成。
正如documentation所说:
[PutObjectAsync]启动PutObject操作的异步执行。
因为您没有等待方法完成,所以代码会继续并尝试删除文件(两次!),同时文件仍在上传。
解决此问题的最简单方法是更改代码以使用synchronous version:
client1.PutObject(Request);