C#: downloading and attaching PDFs to MailMessage are corrupt

76 views Asked by At

I am trying to first download a pdf as a string and then attach it to a MailMessage. Here is what I have done so far

string htmlAttachment = webClient.DownloadString((HttpUtility.HtmlDecode(dictIterator.Value)));
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(htmlAttachment);
writer.Flush();
stream.Position = 0;
msg.Attachments.Add(new Attachment((Stream)stream, dictIterator.Key));

But whenever I open the pdf attachment, it says, Insufficient data for an image'. Is it something related to encoding and should I directly download it as a stream rather than first getting it asstring`??

1

There are 1 answers

0
Vikas Gupta On

Yes, you should download the file in Binary (Not as string.. No encoding involved.. Just pure binary).


PS - Try also saving the file locally to the disk, before attaching it. And then open it from the disk. It will eliminate the unlikely possibility of MailMessage being the problem.