1

我正在使用此功能将报告写入 pdf 文件并将其作为电子邮件附件发送。

string strNovaQueryString = string.Empty;
string pathFile = "";

string[] fields;
string[] values;

fields = ParamRelatorio.Split('|');

foreach (string key in fields)
{
    string[] param= key.Split(new char[] { '=' });
    strNovaQueryString += param[0] + "=" + param[1] + "&";
}

if (!string.IsNullOrEmpty(strNovaQueryString))
    strNovaQueryString = strNovaQueryString.TrimEnd('&');

string url = reportURL + "/ViewReport.aspx?" + strNovaQueryString;

string userName = user;
string password = pass;
string strPostData = String.Format("user={0}&pass={1}", userName, password);
byte[] postData = Encoding.ASCII.GetBytes(strPostData);

System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
req.ContentLength = postData.Length;

System.IO.Stream outputStream = req.GetRequestStream();
outputStream.Write(postData, 0, postData.Length);
outputStream.Close();

System.Net.HttpWebResponse rep = (System.Net.HttpWebResponse)req.GetResponse();
System.IO.Stream str = rep.GetResponseStream();
string contentType = rep.ContentType;

string fileType = "";

if (contentType != null)
{
    string[] splitString = contentType.Split(';');
    fileType = splitString[0];
}

if (fileType != null && fileType.ToLower() == "application/pdf")
{

    byte[] buffer = new byte[8192];

    int bytesRead = str.Read(buffer, 0, 8192);

    while (bytesRead > 0)
    {
        byte[] buffer2 = new byte[bytesRead];
        System.Buffer.BlockCopy(buffer, 0, buffer2, 0, bytesRead);

        pathFile = attPath+ "reportName" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";

        BinaryWriter binaryWriter = new BinaryWriter(File.Open(pathFile, FileMode.Create));
        binaryWriter.Write(buffer2);
        binaryWriter.Close();

        bytesRead = str.Read(buffer, 0, 8192);
    }

}
return pathFile;

它正在我想要的路径中保存一个 pdf 文件(类似于“C://Documents//Att”),但 pdf 文件是空的。正在发送电子邮件,但 pdf 为空。我认为这binaryWriter.Write(bytesRead);没有按预期工作,或者变量为空。

有什么建议么?

4

2 回答 2

1

尝试使用System.IO.File.WriteAllBytes(string path, byte[] bytes)而不是BinaryWriter. 它简单得多。在此处查看 MSDN 文章:

https://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes%28v=vs.110%29.aspx

于 2015-06-10T21:12:49.847 回答
1

您不调用 Stream.Flush,但关闭流(关闭不保证调用 Flush)

并且始终使用 using(var stream= ... ) - 因为您必须确保该文件不会被阻塞。

于 2015-06-10T21:41:11.950 回答