1

我是 .net core 和 c# 的新手。我的项目中有文件上传要求。我正在尝试将我的文件上传到 aws s3。我从项目根文件夹中的文件夹上传文件,然后从那里删除上传的文件。但是当我尝试上传到 s3 时出现以下错误

The process cannot access the file because it is being used by another process.

这是我上传文件的代码

string fileFolder = Path.Combine(hostingEnvironment.WebRootPath, "TempFiles");
                    uniqueFileName1 = Guid.NewGuid().ToString() + "_" + cm.UDocument1.FileName;
                    string filePath = Path.Combine(fileFolder, uniqueFileName1);
                    cm.UDocument1.CopyTo(new FileStream(filePath, FileMode.Create));

                    var tempPath = Path.Combine(hostingEnvironment.WebRootPath, "TempFiles", Path.GetFileName(uniqueFileName1));
                    UploadFile(cm.UDocument1,tempPath);

[HttpPost]
    public ActionResult UploadFile(IFormFile file,string path)
    {

        var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion);

        var fileTransferUtility = new TransferUtility(s3Client);
        try
        {
            if (file.Length > 0)
            {

                var fileTransferUtilityRequest = new TransferUtilityUploadRequest
                {
                    BucketName = bucketName,
                    FilePath = path,
                    StorageClass = S3StorageClass.Standard,
                    Key = file.FileName
                };
                fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
                fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
                fileTransferUtility.Upload(fileTransferUtilityRequest);
                fileTransferUtility.Dispose();

                string[] tmp = { "" };
                tmp = fileName.Split("-");

            }
            ViewBag.Message = "File Uploaded Successfully!!";

            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
        }

        return ViewBag.Message;

    }

我该怎么办?

4

1 回答 1

1

在这条线上:

cm.UDocument1.CopyTo(new FileStream(filePath, FileMode.Create));

您创建了一个文件流,但您不处置它。

改为使用 using 语句:

using (var iNeedToLearnAboutDispose = new FileStream(filePath, FileMode.Create))
{
    cm.UDocument1.CopyTo(iNeedToLearnAboutDispose);
}
于 2020-05-21T08:58:54.220 回答