首页 > 解决方案 > (ObjectDisposedException) 无法将 FormFile 上传到磁盘空间

问题描述

我需要单元测试方法

在这里,我从磁盘实例化新的 FormFile

这里我使用静态方法,带有文件和文件夹路径

var id= await ContentSaver.Save(file, path + "\\");

比我尝试将该文件保存回磁盘

并且 VS 抛出异常“System.ObjectDisposedException:无法访问已关闭的文件。” 如何解决?

这是堆栈跟踪

标签: c#asp.net.netasp.net-core.net-core

解决方案


第一个代码部分的答案(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.

推荐阅读