gpt4 book ai didi

C# 下载带简历的文件(Content-Range)

转载 作者:行者123 更新时间:2023-12-05 02:18:34 24 4
gpt4 key购买 nike

我们是否有一些 C# 库或类可以分部分下载大文件,如果连接失败恢复下载?

我试过使用一些内置的 WebClient 类,但它不支持恢复下载。

WebClient webClient = new WebClient();
webClient.DownloadFile(link, @"C:\Test\1.zip");

失败并出现异常:“从传输流中收到意外的 EOF 或 0 字节”。

最佳答案

我编写了一些代码来下载支持简历的文件。

    static bool DownloadFileWithRange()
{
string link = "http://freelistenonline.com/"; //<- link to some big file
string FilePath = @"C:\Test\1.zip";

if (File.Exists(FilePath))
File.Delete(FilePath);

long totalBytesRead = 0;
long MaxContentLength = 0;
long RequestContentLength = 0;
int i = 0;
while (MaxContentLength == 0 || totalBytesRead < MaxContentLength)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);

if (totalBytesRead > 0) request.AddRange(totalBytesRead);

WebResponse response = request.GetResponse();

Console.WriteLine("=============== Request #{0} ==================", ++i);
foreach (var header in response.Headers)
{
if (header.ToSaveString().Contains("Content-Length") || header.ToSaveString().Contains("Content-Range"))
Console.WriteLine("{0}: {1}", header, response.Headers[header.ToString()]);
}

if (response.ContentLength > MaxContentLength)
MaxContentLength = response.ContentLength;

var ns = response.GetResponseStream();
RequestContentLength = 0;
try
{
using (var responseStream = response.GetResponseStream())
{
using (FileStream localFileStream = new FileStream(FilePath, FileMode.Append))
{
var buffer = new byte[4096];
int bytesRead;

while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytesRead += bytesRead;
RequestContentLength += bytesRead;
localFileStream.Write(buffer, 0, bytesRead);
}

Console.WriteLine("Got bytes: {0}", RequestContentLength);
}

}
}
catch (Exception ex)
{
Console.WriteLine("Got bytes: {0}", RequestContentLength);
}
}

if (MaxContentLength == totalBytesRead)
return true;

return false;
}

关于C# 下载带简历的文件(Content-Range),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44935273/

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