ASP .NET Core 3.1 IFormFile 从主机读取文件

ASP .NET Core 3.1 IFormFile read a file from hosting

我想从主机向注册用户发送一个文件,并将确认电子邮件作为附件。

我的电子邮件发件人 class 接受包含 public IFormFileCollection Attachments { get; set; }

的消息模型

我的问题:我无法从托管中读取文件并将其转换为 IFormFile。

这是我的代码块:

var pathToEmailAttachment = _webHostEnvironment.WebRootPath
+ Path.DirectorySeparatorChar.ToString()
+ "pdf"
+ Path.DirectorySeparatorChar.ToString()
+ "MyFile.pdf";

IFormFile file;

using (var stream = System.IO.File.OpenRead(pathToEmailAttachment))
{
    file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name));
}

var message = new Message(new string[] { user.Email }, messageSubject, emailMessage, new FormFileCollection() { file });

await _emailSender.SendEmailAsync(message);

消息模型:

public class Message
{
    public List<MailboxAddress> To { get; set; }
    public string Subject { get; set; }
    public string Content { get; set; }
    public IFormFileCollection Attachments { get; set; }

    public Message()
    {

    }

    public Message(IEnumerable<string> to, string subject, string content, IFormFileCollection attachments)
    {
        To = new List<MailboxAddress>();

        To.AddRange(to.Select(x => new MailboxAddress(x, x)));
        Subject = subject;
        Content = content;
        Attachments = attachments;
    }
}

如有任何建议或帮助,我们将不胜感激。

可能有 2 个问题,FormFile 实例化不正确和文件流提前关闭。因此,您可以尝试在 的帮助下修复 FormFile 创建并扩展 using 语句

using (var stream = System.IO.File.OpenRead(pathToEmailAttachment))
{
    file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
    {
        Headers = new HeaderDictionary(),
        ContentType = "you content type"
    };

    var message = new Message(new string[] { user.Email }, messageSubject, emailMessage, new FormFileCollection() { file });

    await _emailSender.SendEmailAsync(message);
}