2017-01-03 58 views
0

我想上传带有http post的文件。下面的方法工作正常,但与文件> 1GB我得到OutOfMemoryExceptions使用System.Net.WebClient上传文件时出现OutOfMemoryException

我发现基于一些solutionsAllowWriteStreamBufferingSystem.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); 
      } 
     } 
    } 
} 

什么我需要改变,以避免这个错误?

+0

你有没有使用[WebClient.UploadFileAsync]考虑(https://msdn.microsoft.com/en-us /library/ms144232(v=vs.110).aspx)? –

+0

这些问题需要记录安装的反恶意软件产品。并显示启用了非托管调试的堆栈跟踪。 –

回答

1

经过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; 
    } 
} 
相关问题