。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;
}
我该怎么办?
在此行:
cm.UDocument1.CopyTo(new FileStream(filePath, FileMode.Create));
您创建了文件流,但是没有丢弃它。
改为使用using语句:
using (var iNeedToLearnAboutDispose = new FileStream(filePath, FileMode.Create))
{
cm.UDocument1.CopyTo(iNeedToLearnAboutDispose);
}