1

我尝试download file via WebClient,但它不是从文件中返回所有字节。Original file has 45Kb,它download only 8kb来自总文件。它发生在我添加用户代理标头之后。

我的代码是:

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

4

1 回答 1

1

可能是错误消息或类似的东西。您可能并没有真正从文件中下载字节。尝试将结果作为字符串读取,以查看它是否不是错误消息。或者尝试从 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); 
> }
于 2012-11-02T09:47:25.933 回答