[英]OutOfMemoryException while uploading file with System.Net.WebClient
我想上传带有http帖子的文件。 以下方法工作正常,但文件大于1GB时出现OutOfMemoryExceptions
我发现了一些基于AllowWriteStreamBuffering
和System.Net.WebRequest
解决方案 ,但在这种情况下似乎没有帮助,因为我需要使用System.Net.WebClient
进行解决。
引发异常时,我的应用程序的内存使用率始终约为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);
}
}
}
}
为了避免此错误,我需要更改什么?
经过1天的尝试,我找到了解决此问题的方法。
也许这会帮助将来的访客
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);
}
}
}
}
扩展的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.