1

I am working on ASP.Net MVC 4.7 project, in which I am using Microsoft graph api to send mail. I want to know what is the contentByte. How I can get it from the filestream. See the following code. I am searching for

fileAttachment.ContentBytes=

Note that files are in stream they are uploaded by the user.

private static MessageAttachmentsCollectionPage GetAttachments(List<HttpPostedFileBase> fileUploader)
    {
        var attachmentPage = new MessageAttachmentsCollectionPage();
        if (fileUploader != null)
        {
            foreach (var file in fileUploader)
            {
                var fileAttachment = new FileAttachment();
                fileAttachment.Name = file.FileName;
                fileAttachment.ContentType = file.ContentType;
                fileAttachment.ContentBytes = ??

                attachmentPage.Add(fileAttachment);
            }
        }
Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
Jashvita
  • 553
  • 3
  • 24

1 Answers1

0

This is just a base64-encoded contents of the file (string). For example:

public static class StreamExtensions
{
    public static string ConvertToBase64(this Stream stream)
    {
        if (stream is MemoryStream memoryStream)
        {
            return Convert.ToBase64String(memoryStream.ToArray());
        }

        var bytes = new Byte[(int)stream.Length];

        stream.Seek(0, SeekOrigin.Begin);
        stream.Read(bytes, 0, (int)stream.Length);

        return Convert.ToBase64String(bytes);
    }
}

You may find different approaches described in the Encode a FileStream to base64 with c# thread.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • When I used this code and assigned to fileAttachment.ContentByte. It throw an error "Cannot implicitly convert type 'string' to 'Byte[]'. – Jashvita Apr 19 '22 at 17:02
  • By the way it did work but excel file throws an error when I tried to open it from the email. "Excel cannot open the file because the file format or file extension is not valid..." – Jashvita Apr 21 '22 at 05:23