在下载完成后定期从HttpWebRequest写入文件?

时间:2010-04-18 20:49:41

标签: c# httpwebrequest

现在我正在使用此代码下载文件(带有Range标头)。大多数文件都很大,并且当文件下载时,它目前运行99%的CPU。是否有任何方法可以定期写入文件,以便它不会一直保留在RAM中?

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);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

不是将数据写入MemoryStream(将数据存储在内存中),而是将数据写入FileStream(将数据存储在磁盘上的文件中)。

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 (FileStream fileStream = File.Create(path))
{
    stream.CopyTo(fileStream);
}