2012-08-16 6 views
6

.NET 네임 스페이스가 제공하는 WebClient 개체를 통해 FTP 서버에서 파일을 다운로드 한 다음 BinaryWriter을 통해 실제 파일에 바이트를 씁니다. 모두 좋은. 그러나 이제는 파일의 크기가 급격히 증가했으며 메모리 제약이 걱정되어 다운로드 스트림을 만들고 파일 스트림을 만들고 라인에서 파일을 다운로드하여 파일에 씁니다.FTP에서 로컬 저장소로 파일을 다운로드하는 Webclient Stream

나는 이것의 좋은 예를 찾을 수 없어서 긴장되어 있습니다. 내 최종 결과는 다음과 같습니다.

var request = new WebClient(); 

// Omitted code to add credentials, etc.. 

var downloadStream = new StreamReader(request.OpenRead(ftpFilePathUri.ToString())); 
using (var writeStream = File.Open(toLocation, FileMode.CreateNew)) 
{ 
    using (var writer = new StreamWriter(writeStream)) 
    { 
     while (!downloadStream.EndOfStream) 
     { 
      writer.Write(downloadStream.ReadLine());     
     } 
    } 
} 

이 잘못된/더 좋은 방법 등이 있습니까?

답변

8

WebClient 클래스의 다음 사용법을 사용해 보셨습니까? 당신이 사용자 정의 된 버퍼 크기를 사용하여 명시 적으로 파일을 다운로드하려면

using (WebClient webClient = new WebClient()) 
{ 
    webClient.DownloadFile("url", "filePath"); 
} 

는 업데이트

using (var client = new WebClient()) 
using (var stream = client.OpenRead("...")) 
using (var file = File.Create("...")) 
{ 
    stream.CopyTo(file); 
} 

는 : 나는 여전히

public static void DownloadFile(Uri address, string filePath) 
{ 
    using (var client = new WebClient()) 
    using (var stream = client.OpenRead(address)) 
    using (var file = File.Create(filePath)) 
    { 
     var buffer = new byte[4096]; 
     int bytesReceived; 
     while ((bytesReceived = stream.Read(buffer, 0, buffer.Length)) != 0) 
     { 
      file.Write(buffer, 0, bytesReceived); 
     } 
    } 
} 
+0

예, 그리고 (요청 객체는 웹 클라이언트 [나 '입니다 m 내 게시물을 업데이트하여 표시]])하지만 DownladFile은 전체 파일을 메모리에 제공합니다. 내가 찾고있는 것과 반대입니다. – OnResolve

+0

@OnResolve, 죄송합니다. 언급했다. 업데이트를 참조하십시오. –

+0

@OnResolve, 맞춤 버퍼 크기로 버전을 추가했습니다. –

관련 문제