2017-01-03 3 views
0

http 게시글을 사용하여 파일을 업로드하고 싶습니다. 다음 방법은 잘 작동하지만, 파일> 1GB의 난 AllowWriteStreamBufferingSystem.Net.WebRequest에 따라 일부 solutions을 발견하지만 난 System.Net.WebClient으로 해결해야하기 때문에 그 도움이 경우에있을 것 같지 않는 OutOfMemoryExceptionsSystem.Net.WebClient를 사용하여 파일을 업로드하는 동안 OutOfMemoryException이 발생했습니다.

를 얻을.

예외가 슬로우됩니다 내 응용 프로그램의 메모리 사용량이 ~ 약 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

는 https://msdn.microsoft.com/en-us (당신이 [WebClient.UploadFileAsync]를 사용하여 고려 되세요 /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; 
    } 
} 
관련 문제