2012-11-02 25 views
1

我嘗試download file via WebClient,但它並不返回來自文件的所有字節。 Original file has 45Kb,It download only 8kb從總文件。它發生在我添加用戶代理標題後。System.Net.WebClient不是返回文件中的所有數據

我的代碼是:

using (ZipFile zip = new ZipFile()) 
{ 
    foreach (KeyValuePair<string, string> i in filesToInclude) 
    { 
     System.Net.WebClient wc = new System.Net.WebClient(); 
     wc.Credentials = System.Net.CredentialCache.DefaultCredentials; 
     wc.UseDefaultCredentials = true; 
     wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 
     string downloadUrl = SPContext.Current.Site.Url + i.Key;  
     AppClass.WriteToLog(string.Format("downloadUrl: {0}", downloadUrl)); 
     byte[] img = wc.DownloadData(downloadUrl); 
     zip.AddEntry(i.Value, img); 
     } 
     zip.Save(Response.OutputStream); 
    } 

你有什麼想法?

更新:在以前的版本url無法正確構建。我將我的代碼更改爲:

using (ZipFile zip = new ZipFile()) 
{ 
    foreach (KeyValuePair<string, string> i in filesToInclude) 
    { 
      System.Net.WebClient wc = new System.Net.WebClient(); 
      wc.Credentials = System.Net.CredentialCache.DefaultCredentials; 
      wc.UseDefaultCredentials = true; 
      wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 
      string downloadUrl = SPContext.Current.Site.Url + i.Key; 
      Uri uri = new Uri(downloadUrl); 
      AppClass.WriteToLog(string.Format("downloadUrl: {0}\nUri.AbsoluteUri: {1}", downloadUrl, uri.AbsoluteUri)); 
      byte[] img = wc.DownloadData(uri.AbsoluteUri); 

      if (!wc.ResponseHeaders.Get(0).Contains("OK")) 
      { 
       AppClass.WriteToLog("Unable to donwload the file"); 
      } 
      zip.AddEntry(i.Value, img); 
     } 

     zip.Save(Response.OutputStream); 
} 

現在我還有另一個問題。 The remote server returned an error: (403) Forbidden

+0

可能是錯的,但它可以是Apache正在認識到Firefox支持gzip壓縮併發送文件gzip壓縮,如果在那裏有gzip,試着用wireshark查看頭文件,我的權利。 – Tearsdontfalls

回答

1

可能是錯誤消息或類似的東西。你可能不是真的從文件中下載字節。 嘗試以字符串的形式讀取結果以查看它是否不是err消息。或嘗試從WebClient獲取HTTP響應代碼。

這是一個糟糕的方式做到這一點,但你應該做一些錯誤檢查這樣的:

> using (ZipFile zip = new ZipFile()) { 
>  foreach (KeyValuePair<string, string> i in filesToInclude) 
>  { 
>   System.Net.WebClient wc = new System.Net.WebClient(); 
>   wc.Credentials = System.Net.CredentialCache.DefaultCredentials; 
>   wc.UseDefaultCredentials = true; 
>   wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 
>   string downloadUrl = SPContext.Current.Site.Url + i.Key;  
>   AppClass.WriteToLog(string.Format("downloadUrl: {0}", downloadUrl)); 
>   byte[] img = wc.DownloadData(downloadUrl); 
>   if (!wc.ResponseHeaders[0].Contains("OK")) 
>   { 
>   throw new Exception("Unable to donwload the file"); 
>   } 
>   zip.AddEntry(i.Value, img); 
>  } 
>  zip.Save(Response.OutputStream); 
> } 
+1

應該是評論還是? – Tearsdontfalls

+0

抱歉等待,但我的本地網絡臨時不起作用,我無法檢查您的示例 – user571874

+0

是的。你是對的。我的網址不正確。我更改了構建Url的代碼,現在我又遇到了另一個問題。看看這個帖子 – user571874