简体   繁体   English

使用System.Net.WebClient上传文件时出现OutOfMemoryException

[英]OutOfMemoryException while uploading file with System.Net.WebClient

I want to upload a file with http post. 我想上传带有http帖子的文件。 The following method works fine but with files >1GB I get a OutOfMemoryExceptions 以下方法工作正常,但文件大于1GB时出现OutOfMemoryExceptions

I found some solutions based on AllowWriteStreamBuffering and System.Net.WebRequest but that doesn't seem help be in this case because I need to solve it with System.Net.WebClient . 我发现了一些基于AllowWriteStreamBufferingSystem.Net.WebRequest 解决方案 ,但在这种情况下似乎没有帮助,因为我需要使用System.Net.WebClient进行解决。

The memory usage of my application when the exception is thrown is always about ~500MB 引发异常时,我的应用程序的内存使用率始终约为500MB

string file = @"C:\test.zip";
string url = @"http://foo.bar";
using (System.Net.WebClient client = new System.Net.WebClient())
{
    using (System.IO.Stream fileStream = System.IO.File.OpenRead(file))
    {
        using (System.IO.Stream requestStream = client.OpenWrite(new Uri(url), "POST"))
        {
            byte[] buffer = new byte[16 * 1024];
            int bytesRead;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                requestStream.Write(buffer, 0, bytesRead);
            }
        }
    }
}

What do I need to change to avoid this error? 为了避免此错误,我需要更改什么?

After 1 Day of trying I found a solution for this issue. 经过1天的尝试,我找到了解决此问题的方法。

Maybe this will help some future visitors 也许这会帮助将来的访客

string file = @"C:\test.zip";
string url = @"http://foo.bar";
using (System.IO.Stream fileStream = System.IO.File.OpenRead(file))
{
    using (ExtendedWebClient client = new ExtendedWebClient(fileStream.Length))
    {
        using (System.IO.Stream requestStream = client.OpenWrite(new Uri(url), "POST"))
        {
            byte[] buffer = new byte[16 * 1024];
            int bytesRead;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                requestStream.Write(buffer, 0, bytesRead);
            }
        }
    }
}

Extended WebClient method 扩展的WebClient方法

private class ExtendedWebClient : System.Net.WebClient
{
    public long ContentLength { get; set; }
    public ExtendedWebClient(long contentLength)
    {
        ContentLength = contentLength;
    }

    protected override System.Net.WebRequest GetWebRequest(Uri uri)
    {
        System.Net.HttpWebRequest hwr = (System.Net.HttpWebRequest)base.GetWebRequest(uri);
        hwr.AllowWriteStreamBuffering = false; //do not load the whole file into RAM
        hwr.ContentLength = ContentLength;
        return (System.Net.WebRequest)hwr;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM