Home > OS >  ASP .NET Core 3.1 IFormFile read a file from hosting
ASP .NET Core 3.1 IFormFile read a file from hosting

Time:12-28

I would like to send a file from the hosting to the registered user with the confirmation email as an attachment.

My email sender class accepts Message model that contains public IFormFileCollection Attachments { get; set; }

My issue: I can not read the file from hosting and convert it to IFormFile.

This is a chunk of my code:

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);

Message Model:

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;
    }
}

Debug Image

Any advice or assistance would be greatly appreciated.

CodePudding user response:

There might be 2 problems, incorrect FormFile instantiation and early closing of file stream. So you can try to fix FormFile creation with help of this answer and extend using statement

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);
}
  • Related