asp.net-core - 如何在 .netcore 中关闭文件流
问题描述
我是 .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);
}
推荐阅读
- full-text-search - Couchbase 全文搜索 (FTS) - 如何返回存储桶数据?
- c - SSE2 和内联装配插入结构
- database - 后端:远程与本地 sql 数据库
- excel - 如何使用 Wkst 2 上的数据透视表按 wkst 1 中的单元格值过滤数据透视表。如何修改我的代码?
- c - 如何在嵌入式上比较字符串日期 GMT
- c# - 即使在将属性数据属性设置为“NotMapped”之后,也会出现“无效的列名 ...”
- javascript - 如何将文件名数组转换为 JSON 并添加密钥
- sql - 汇总未按预期聚合
- cassandra - Cassandra 或其他 nosql 数据库中的少对多建模
- r - geom_text 的位置参数设置不同的标签