简体   繁体   中英

C#: downloading and attaching PDFs to MailMessage are corrupt

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 as 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 as string`??

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM