首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BinaryWriter.Write未创建.pdf文件

BinaryWriter.Write未创建.pdf文件
EN

Stack Overflow用户
提问于 2015-06-11 04:56:55
回答 2查看 1.3K关注 0票数 1

我使用此函数将报告写入pdf文件,并将其作为附件发送到电子邮件中。

代码语言:javascript
复制
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);没有像预期的那样工作,或者变量为空。

有什么建议吗?

EN

回答 2

Stack Overflow用户

发布于 2015-06-11 05:12:50

尝试使用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

票数 1
EN

Stack Overflow用户

发布于 2015-06-11 05:41:12

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

并始终使用using(var stream= ... )-因为您必须确保该文件将被解锁。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30767160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档