2017-01-03 62 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; 
    } 
} 
相關問題