2011-01-10 82 views
4

我在下载pdf文件时遇到问题。而下载其他文件。 代码:代码在C#中下载PDF文件

WebClient client = new WebClient(); 
client.DownloadFile(remoteFilename, localFilename); 

请帮助我,如果你知道

+7

问题是什么? – 2011-01-10 07:21:33

+0

我的问题是在下载PDF文件并将其保存为上述代码的PDF文档之后。文我试图打开它显示文件修复错误。 – 2011-01-10 11:11:22

回答

8

检查这种方法,希望帮助

 public static void DownloadFile(HttpResponse response,string fileRelativePath) 
    { 
     try 
     { 
      string contentType = ""; 
      //Get the physical path to the file. 
      string FilePath = HttpContext.Current.Server.MapPath(fileRelativePath); 

      string fileExt = Path.GetExtension(fileRelativePath).Split('.')[1].ToLower(); 

      if (fileExt == "pdf") 
      { 
       //Set the appropriate ContentType. 
       contentType = "Application/pdf"; 
      } 

      //Set the appropriate ContentType. 
      response.ContentType = contentType; 
      response.AppendHeader("content-disposition", "attachment; filename=" + (new FileInfo(fileRelativePath)).Name); 

      //Write the file directly to the HTTP content output stream. 
      response.WriteFile(FilePath); 
      response.End(); 
     } 
     catch 
     { 
      //To Do 
     } 
    } 
1

@Syed Mudhasir: 它只是一个行:)

client.DownloadFileAsync(new Uri(remoteFilename, UriKind.Absolute), localFilename); 

它将下载pdf文件。 :)

3

请尝试下面的代码示例下载.pdf文件。

Response.ContentType = "Application/pdf"; 
Response.AppendHeader("Content-Disposition", "attachment; filename=Test_PDF.pdf"); 
Response.TransmitFile(Server.MapPath("~/Files/Test_PDF.pdf")); 
Response.End(); 
-1

这为我工作:

string strURL = @"http://192.168.1.xxx/" + sDocumento; 
WebClient req = new WebClient(); 
HttpResponse response = HttpContext.Current.Response; 
response.Clear(); 
response.ClearContent(); 
response.ClearHeaders(); 
response.Buffer = true; 
response.AddHeader("Content-Disposition", "attachment;filename=\"" + sDocumento + "\""); 
byte[] data = req.DownloadData(strURL); 
response.BinaryWrite(data); 
response.End();