C# WebStream 寻求以“块”形式下载文件

发布于 2024-11-28 11:11:12 字数 903 浏览 0 评论 0原文

我正在尝试用 C# 编写一个小程序通过 HTTP 下载文件。 使用 WebClient 进行基本下载效果很好,但现在我想尝试一下 使用多个连接下载文件。 到目前为止:

HttpWebRequest HttpRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse HttpResponse = (HttpWebResponse)HttpRequest.GetResponse();
Stream ResponseStream = HttpResponse.GetResponseStream();

FileStream FSChunk = new FileStream(destination, FileMode.OpenOrCreate, FileAccess.Write);

while ((BytesThisRead = ResponseStream.Read(Buffer, 0, (int)BytesPerRead)) != 0)
{
    FSChunk.Write(Buffer, 0, BytesThisRead);
    TotallyRead += BytesThisRead;
    if (TotalReadLength - TotallyRead < buffersize)
        BytesPerRead = TotalReadLength - TotallyRead;
}

我可以使用这个 ResponseStream 下载文件,也可以使用一个 ResponseStream 将文件分成两部分。我的问题是,WebStream 不可查找,所以我不能只设置读取位置。 我如何设法使用不同的流(连接,我认为一个流不能被多个成员使用)同时通过 HTTP 下载一个文件。 我在这里读了很多文章并用谷歌搜索了几个小时,但我找不到解决方案。 分块传输编码与这个主题有什么关系吗?

此致, 达蒙

I'm trying to make a small programm to download files via HTTP in C#.
The Basic download with a WebClient works fine, but now i wanted to try
downloading a file with multiple connections.
So far:

HttpWebRequest HttpRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse HttpResponse = (HttpWebResponse)HttpRequest.GetResponse();
Stream ResponseStream = HttpResponse.GetResponseStream();

FileStream FSChunk = new FileStream(destination, FileMode.OpenOrCreate, FileAccess.Write);

while ((BytesThisRead = ResponseStream.Read(Buffer, 0, (int)BytesPerRead)) != 0)
{
    FSChunk.Write(Buffer, 0, BytesThisRead);
    TotallyRead += BytesThisRead;
    if (TotalReadLength - TotallyRead < buffersize)
        BytesPerRead = TotalReadLength - TotallyRead;
}

I can download the File using this one ResponseStream, also split up in 2 parts using the one ResponseStream. My problem is, the WebStreams are not seekable, so I can't just set a position to read from.
How can I manage to download one File over HTTP simultaneously using different Streams (connections, I think one stream can't be used by multiple members).
I've read a lot of articles here and googled for some hours, but I can't find a solution.
Does Chunked transfer encoding have anything to do with this topic?

Best Regards,
Damon

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

往事随风而去 2024-12-05 11:11:13

您需要在请求中调用AddRange - 这会在http header中设置一个内容范围,告诉服务器您是文件的哪一部分要求。

请参阅http://msdn.microsoft.com/en-us/library/dd992108。 ASPX

you need to call AddRange on the request - this set a content range in the http header which tells the server which portion of the file you are asking for.

see http://msdn.microsoft.com/en-us/library/dd992108.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文