[英]downloading a zip file from URL in wcf c#
我正在嘗試從URL下載一個zip文件夾。 該URL指向Sharepoint中包含文檔集的庫。 如果將網址粘貼到瀏覽器中,則會下載一個zip文件。 在嘗試通過代碼執行相同操作時,我只能下載32426個字節。 我嘗試了兩種方法-一種使用WebClient的DownloadDataAsync(),另一種使用WebRequest和響應。 這兩個文件都只能讀取32426個字節,而zip文件夾中的文件大小接近6 MB。
using (var Webclient1 = new WebClient())
{
Webclient1.Headers.Add("Accept: text/html, application/xhtml+xml, */*");
Webclient1.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
byte[] data = null;
Webclient1.DownloadDataCompleted +=
delegate(object sender, DownloadDataCompletedEventArgs e)
{
data = e.Result;
};
Webclient1.DownloadDataAsync(uri);
while (Webclient1.IsBusy)
{
System.Threading.Thread.Sleep(10000);
}
var len = data.Length;
}
使用HttpRequest和響應
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
//request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Accept = @"text/html, application/xhtml+xml, */*";
request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)";
request.Timeout = 1000000;
using (var response = request.GetResponse())
{
MemoryStream stream2 = new MemoryStream();
var stream = response.GetResponseStream();
stream.CopyTo(stream2);
return stream2.ToArray();
}
兩者都讀取不完整的內容。
這應該工作:
public bool DownloadFile(string itemUrl, string localPath)
{
bool downloadSuccess = false;
try
{
using (IOFile.Stream itemFileStream = GetItemAsStream(itemUrl))
{
using (IOFile.Stream localStream = IOFile.File.Create(localPath))
{
itemFileStream.CopyTo(localStream);
downloadSuccess = true;
}
}
}
catch (Exception err)
{
}
return downloadSuccess;
}
protected IOFile.Stream GetItemAsStream(string itemUrl)
{
IOFile.Stream stream = null;
try
{
FileInformation fileInfo = File.OpenBinaryDirect(_context, itemUrl);
stream = fileInfo.Stream;
}
catch (Exception err)
{
throw new ApplicationException(string.Format("Error executing method {0}. {1}", MethodBase.GetCurrentMethod().Name, err.Message));
}
return stream;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.