gpt4 book ai didi

c# - 从 wcf c# 中的 URL 下载 zip 文件

转载 作者:太空宇宙 更新时间:2023-11-03 15:30:10 32 4
gpt4 key购买 nike

我正在尝试从 url 下载 zip 文件夹。该 url 指向 Sharepoint 中包含文档集的库。如果 url 粘贴在浏览器中,它会下载一个 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;
}

关于c# - 从 wcf c# 中的 URL 下载 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34057552/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com