red79phoenix
red79phoenix

Reputation: 91

c# Write file to S3 and then delete the local file

The following program pulls data from a web service writes it to a csv, uploads the file to S3 and then deletes it. The problem I am having is that it cannot delete the file because it says "System.IO.IOException: 'The process cannot access the file 'file.csv' because it is being used by another process.", I am guessing it has not finished writing to S3 because it doesn't show up there. Any suggestions?

Here I close the file, upload to S3 and then try to delete.

outputFile.Flush();
outputFile.Close();
AmazonS3Uploader awsfu = new AmazonS3Uploader();
awsfu.UploadFile(outputfilePath, "api-end-point", filenameaws);
System.IO.File.Delete(@outputfilePath);

The following is the code for the S3 upload

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

    }
}

Upvotes: 0

Views: 1632

Answers (1)

stuartd
stuartd

Reputation: 73253

You're calling an asynchronous method and not waiting for it to complete.

As the documentation says:

[PutObjectAsync] initiates the asynchronous execution of the PutObject operation.

Because you're not waiting for the method to complete, the code continues and tries to delete the file (twice!) while the file is still being uploaded.

The easiest way to fix this is to change your code to use the synchronous version:

client1.PutObject(Request);

Upvotes: 1

Related Questions