定期从HttpWebRequest写入文件还是下载完成后? [英] Writing file from HttpWebRequest periodically vs. after download finishes?

查看:43
本文介绍了定期从HttpWebRequest写入文件还是下载完成后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在使用此代码下载文件(带有Range标头).大多数文件很大,下载文件时它当前正在运行99%的CPU.有什么方法可以定期写入文件,从而使其不会一直保留在RAM中?

Right now I am using this code to download files (with a Range header). Most of the files are large, and it is running 99% of CPU currently as the file downloads. Is there any way that the file can be written periodically so that it does not remain in RAM constantly?

private byte[] GetWebPageContent(string url, long start, long finish)
{
    byte[] result = new byte[finish];
    HttpWebRequest request;

    request = WebRequest.Create(url) as HttpWebRequest;

    //request.Headers.Add("Range", "bytes=" + start + "-" + finish);

    request.AddRange((int)start, (int)finish);

    using (WebResponse response = request.GetResponse())
    {
        return ReadFully(response.GetResponseStream());
    }    
}

public static byte[] ReadFully(Stream stream)
{
    byte[] buffer = new byte[32768];
    using (MemoryStream ms = new MemoryStream())
    {
        while (true)
        {
            int read = stream.Read(buffer, 0, buffer.Length);
            if (read <= 0)
                return ms.ToArray();
            ms.Write(buffer, 0, read);
        }
    }
}

推荐答案

而不是将数据写入

Instead of writing the data to a MemoryStream (which stores the data in memory), write the data to a FileStream (which stores the data in a file on disk).

byte[] buffer = new byte[32768];
using (FileStream fileStream = File.Create(path))
{
    while (true)
    {
        int read = stream.Read(buffer, 0, buffer.Length);
        if (read <= 0)
            break;
        fileStream.Write(buffer, 0, read);
    }
}

使用.NET 4.0:

Using .NET 4.0:

using (FileStream fileStream = File.Create(path))
{
    stream.CopyTo(fileStream);
}

这篇关于定期从HttpWebRequest写入文件还是下载完成后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆