将报告从报告查看器导出到内存流,然后通过电子邮件发送报告

Export report from report viewer to memory stream and then email report

我目前有一个显示本地报告的页面(它在我的网页上的报告查看器控件中获取参数。我有一个要求,即用户希望生成报告,然后通过单击按钮或页面通过电子邮件发送加载。我有下面的代码,我曾尝试将报告加载到内存流中,然后通过电子邮件发送。电子邮件部分工作正常,但 pdf 不生成。加载 pdf 和的最佳方法是什么发送电子邮件,因为它不是这样的物理文件?

    WebClient client = new WebClient();
        byte[] bytes = client.DownloadData("http://localhost:51997/ReportDetails.aspx?Report1.rdlc&rs%3aFormat=PDF");

        MemoryStream ms = new MemoryStream(bytes);

        MailMessage mailObj = new MailMessage("FromAddress", "ToAddress", "header", "body text");

        SmtpClient SMTPServer = new SmtpClient("RelayServer");
        mailObj.IsBodyHtml = true;
        mailObj.Attachments.Add(new Attachment(ms, "Reports.pdf"));
        try
        {
            SMTPServer.Send(mailObj);
        }
        catch (Exception)
        {
            throw;
        }

我通过将本地报告加载到字节数组,写入文件流,然后将其加载到内存流,然后我可以在内存流中发送电子邮件来解决这个问题。

  Warning[] warnings;
        string[] streamids;
        string mimeType;
        string encoding;
        string filenameExtension;

        byte[] bytes = ReportViewer1.LocalReport.Render(
           "PDF", null, out mimeType, out encoding, out filenameExtension,
            out streamids, out warnings);


        string filename = Path.Combine(Path.GetTempPath(), "Report2.rdlc");

        using (var fs = new FileStream(filename, FileMode.Create))
        {
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
        }

加载到内存流中:

MemoryStream ms = new MemoryStream(bytes);

然后作为附件发送:

  MailMessage mailObj = new MailMessage("From", "To", "header", "body");

        SmtpClient SMTPServer = new SmtpClient("relayServer");
        mailObj.IsBodyHtml = true;

        mailObj.Attachments.Add(new Attachment(ms, "report.pdf"));

        try
        {
            SMTPServer.Send(mailObj);
        }
        catch (Exception)
        {
            throw;
        }