c# - (ObjectDisposedException) 无法将 FormFile 上传到磁盘空间
问题描述
我需要单元测试方法
这里我使用静态方法,带有文件和文件夹路径
var id= await ContentSaver.Save(file, path + "\\");
并且 VS 抛出异常“System.ObjectDisposedException:无法访问已关闭的文件。” 如何解决?
解决方案
第一个代码部分的答案(https://i.stack.imgur.com/ktjip.png)。您在使用范围内创建流并立即处理它。为避免它将文件的内容复制到 MemoryStream 中(不需要被废弃)并设置为 FormFile 的源
IFormFile formFile;
using (var fstream = new FileStream("path", FileMode.Open))
{
var mstream = new MemoryStream();
fstream.CopyTo(mstream);
formFile = new FormFile(mstream, 0, mstream.Length, null, mstream.Name);
}
// here fstream is disposed, but not mstream, and you can use your FormFile instance
// MemoryStream does not need to be disposed explicitly, it do not posess any OS specific handlers, GC is enought.
推荐阅读
- c++ - C++11 字符数组初始化和字符串字面量
- dart - “as”如何修改List;使用 as, is, ! 进行类型提升 操作员
- react-native - 反应原生右对齐包装文本
- javascript - AWS Lambda 如何读取查询参数
- javascript - 如何使用 gatsby-source-unsplash 在 gatsby 中加载 unsplash 图像
- vba - 如何从已声明变量的串联中获取值?
- google-calendar-api - Google Calendar API 是否支持重复规则中的 FREQ=HOURLY?
- swift - Swift Package Manager - 如何指定本地机器的本地路径和 CI 的 git url?
- c - 在多行中打印函数的返回
- google-apps-script - 谷歌应用脚本,如何更改默认电子邮件字体?