2011-01-28 42 views
5

Tôi đã viết mã sau để lấy nội dung từ một trang web và lưu vào hệ thống. nếu trang web ở định dạng html, tôi có thể lưu nó. nếu trang web ở định dạng pdf tôi không thể lưu nó. Sau khi lưu nếu tôi mở các tập tin trống trang đang đến.sử dụng phản hồi http cách lưu các tệp pdf

Tôi muốn biết Cách lưu tệp pdf khỏi phản hồi.

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(); 

Hãy giúp tôi càng sớm càng tốt.

Trả lời

13

StreamReader.ReadToEnd() trả về một chuỗi. Tệp PDF là nhị phân và chứa dữ liệu không thân thiện với chuỗi. Bạn cần phải đọc nó vào một mảng byte, và ghi mảng byte vào đĩa. Thậm chí tốt hơn, sử dụng một mảng byte nhỏ hơn như một bộ đệm và đọc theo các đoạn nhỏ.

Bạn cũng có thể đơn giản hóa toàn bộ điều bằng cách chỉ sử dụng WebClient: file

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

PDF _usually_ nhị phân, được không? Vì nó dựa trên [PostScript] (http://en.wikipedia.org/wiki/Portable_Document_Format#PostScript), nó có thể chỉ là văn bản, tôi đoán vậy. –

+0

Cảm ơn Joel làm việc tốt. – Vishnu

+0

Phương pháp tuyệt vời. :) +1 sau một năm. –

6
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url); 
WebResponse response = request.GetResponse(); 

using (Stream stream = response.GetResponseStream()) 
using (FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None)) 
{ 
    stream.BlockCopy(fs); 
} 

... 
public static class StreamHelper 
{ 
    public static void Copy(Stream source, Stream target, int blockSize) 
    { 
     int read; 
     byte[] buffer = new byte[blockSize]; 
     while ((read = source.Read(buffer, 0, blockSize)) > 0) 
     { 
      target.Write(buffer, 0, read); 
     } 
    } 
    public static void BlockCopy(this Stream source, Stream target, int blockSize = 65536) 
    { 
     Copy(source, target, blockSize); 
    } 
} 
Các vấn đề liên quan