【问题标题】:Create FormFile from Stream从 Stream 创建 FormFile
【发布时间】:2021-04-15 04:10:41
【问题描述】:

我想在我的种子函数中创建一个 FormFile。但我得到一个空引用异常。这是我的代码

FileStream fs = new FileStream("testfile.jpg", FileMode.Open, FileAccess.Read);
FormFile file = new FormFile(fs, 1024, fs.Length, "testfile", "testfile.jpg");
file.ContentType = "image/jpeg";

当我尝试设置内容类型时会出现空引用。任何想法我做错了什么?之前使用返回 true 的 File.Exists 检查。

【问题讨论】:

  • 您是否尝试过在新的 FileStream 中使用完整路径而不是仅使用文件名?

标签: c# iformfile


【解决方案1】:
using (var stream = File.OpenRead("testfile.jpg"))
  {
     FormFile file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
       {
         Headers = new HeaderDictionary(),
         ContentType = "image/jpeg"
       };
}

完成了工作。似乎 FormFile 需要一个打开的流。在这里找到解决方案:How to instantiate an instance of FormFile in C# without Moq?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 2022-10-21
    • 2021-12-22
    • 1970-01-01
    • 2018-04-14
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多