System.Net.WebClient不返回文件中的所有数据

时间:2012-11-02 09:30:33

标签: asp.net .net webclient webclient-download

我尝试download file via WebClient,但它不返回文件中的所有字节。 Original file has 45Kb,来自总文件的download only 8kb。它发生在我添加 user-agent 标题之后。

我的代码是:

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

1 个答案:

答案 0 :(得分: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); 
> }