HttpClient下载文件OutOfMemory错误

时间:2014-04-16 13:01:50

标签: c# windows-phone httpclient

您好我使用此代码进行文件下载程序功能,但接收文件大小的OutOfMemory Exception。

private async void DownloadFile()
    {

        string url = "http://download.microsoft.com/download/0/A/F/0AFB5316-3062-494A-AB78-7FB0D4461357/Windows_Win7SP1.7601.17514.101119-1850.AMD64CHK.Symbols.msi";
        string filename = "test.msi";

        HttpClientHandler aHandler = new HttpClientHandler();
        aHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
        HttpClient aClient = new HttpClient(aHandler);
        aClient.DefaultRequestHeaders.ExpectContinue = false;
        HttpResponseMessage response = await aClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); // Important! ResponseHeadersRead.

        var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
        var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);

        Stream stream = await response.Content.ReadAsStreamAsync();
        IInputStream inputStream = stream.AsInputStream();
        ulong totalBytesRead = 0;
        while (true)
        {
            // Read from the web.
            IBuffer buffer = new Windows.Storage.Streams.Buffer(1024);
            buffer = await inputStream.ReadAsync(
                buffer,
                buffer.Capacity,
                InputStreamOptions.None);

            if (buffer.Length == 0)
            {
                // There is nothing else to read.
                break;
            }

            // Report progress.
            totalBytesRead += buffer.Length;
            System.Diagnostics.Debug.WriteLine("Bytes read: {0}", totalBytesRead);

            // Write to file.
            await fs.WriteAsync(buffer);

            buffer = null;

        }
        inputStream.Dispose();
        fs.Dispose();
    }

PS。我使用httpclient进行下载,但Windows手机后台传输对wifi有100MB的限制。

1 个答案:

答案 0 :(得分:2)

我在去年处理的一些不同代码中遇到了同样的问题,但是POST而不是GET。不幸的是,我没有找到解决方法,所以我直接使用WebRequest。这是解决方案的片段:

// HttpWebRequest is used here instead of HttpClient as there is no support
// in HttpClient to not buffer uploaded streams, which for our purposes
// causes an OutOfMemoryException to occur.
HttpWebRequest request = WebRequest.Create(ServiceUri.ToString() + requestUri) as HttpWebRequest;
request.ContentLength = content.Length;
request.ContentType = "application/octet-stream";
request.Method = "POST";

request.AllowWriteStreamBuffering = false;  // Prevents OutOfMemoryException

我认为您的修复是以某种方式在使用HttpClient下载时禁用缓冲。