使用HTTP响应如何保存PDF文件 [英] using http response how to save the pdf files

查看:351
本文介绍了使用HTTP响应如何保存PDF文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了下面的代码获取从网页内容,并保存到系统中。
如果网页是HTML格式,我能救它。
如果网页pdf格式我无法保存。节约,如果我运行结束空白页来的文件后。

I've written following code to get the content from a web page and save to the system. if the webpage is in html format i'm able to save it. if the web page is in pdf format i'm unable to save it. After saving if i opend the file blank pages are coming.

我想知道如何将PDF文件从响应保存。

I want to know How to save the pdf files from the response.

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
webContent = reader.ReadToEnd();
StreamWriter sw = new StreamWriter(FileName);
sw.WriteLine(webContent);
sw.Close();

请帮我尽快。

推荐答案

StreamReader.ReadToEnd()返回一个字符串。 PDF文件是二进制的,并且包含不串友好的数据。你需要把它读入一个字节数组,写入字节数组到磁盘。

StreamReader.ReadToEnd() returns a string. PDF files are binary, and contain data that is not string-friendly. You need to read it into a byte array, and write the byte array to disk. Even better, use a smaller byte array as a buffer and read in small chunks.

您还可以通过只使用Web客户端简化了整个事情
$ b

You can also simplify the whole thing by just using webclient:

using (var wc = new System.Net.WebClient())
{
    wc.DownloadFile(Url, FileName);
}

这篇关于使用HTTP响应如何保存PDF文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆