2011-09-14 4 views
0

WebClient 개체를 각각 5 % 씩 사용하여 데이터를 다운로드하려고합니다. 그 이유는 다운로드 한 각 청크에 대해 진행 상황을보고해야하기 때문입니다. 여기 WebClient.OpenRead 청크로 데이터 다운로드

내가이 작업을 수행하기 위해 작성한 코드 :
private void ManageDownloadingByExtractingContentDisposition(WebClient client, Uri uri) 
    { 
     //Initialize the downloading stream 
     Stream str = client.OpenRead(uri.PathAndQuery); 

     WebHeaderCollection whc = client.ResponseHeaders; 
     string contentDisposition = whc["Content-Disposition"]; 
     string contentLength = whc["Content-Length"]; 
     string fileName = contentDisposition.Substring(contentDisposition.IndexOf("=") +1); 

     int totalLength = (Int32.Parse(contentLength)); 
     int fivePercent = ((totalLength)/10)/2; 

     //buffer of 5% of stream 
     byte[] fivePercentBuffer = new byte[fivePercent]; 

     using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) 
     { 
      int count; 
      //read chunks of 5% and write them to file 
      while((count = str.Read(fivePercentBuffer, 0, fivePercent)) > 0); 
      { 
       fs.Write(fivePercentBuffer, 0, count); 
      } 
     } 
     str.Close(); 
    } 

문제는

- 그것은 str.Read()에 도달 할 때, 그것은 전체 스트림을 읽는만큼 일시 정지 한 다음 계산 0 따라서 while()은 작동하지 않습니다. 5Percent 변수만큼만 읽도록 지정 했더라도. 첫 번째 시도에서 전체 스트림을 읽는 것처럼 보입니다.

청크를 올바르게 읽도록하려면 어떻게해야합니까?

감사합니다,

안드레이

+1

WebClient.DownloadProgressChanged 이벤트에 등록한 다음 WebClient.DownloadDataAsync()를 호출하십시오. 이벤트 콜백에서 진행 상황을 업데이트 할 수 있습니다. – Jon

답변

1
do 
{ 
    count = str.Read(fivePercentBuffer, 0, fivePercent); 
    fs.Write(fivePercentBuffer, 0, count); 
} while (count > 0); 
+0

이 작품, 고마워. 왜 그것이 작동하는지 알 수 없습니다. 왜냐하면 while은 count가 수정되기 때문입니다. –

1

당신이 정확한 5 % 청크 크기를 필요로하지 않는 경우, 당신은 DownloadDataAsync 또는 OpenReadAsync 같은 비동기 다운로드 방식으로보고 할 수 있습니다.

새 데이터가 다운로드 될 때마다 DownloadProgressChanged 이벤트가 발생하고 진행률이 변경되며 이벤트는 이벤트 인수에서 완료율을 제공합니다.

일부 예제 코드 :

WebClient client = new WebClient(); 
Uri uri = new Uri(address); 

// Specify a progress notification handler. 
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback); 

client.DownloadDataAsync(uri); 

static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e) 
{ 
    // Displays the operation identifier, and the transfer progress. 
    Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...", 
     (string)e.UserState, 
     e.BytesReceived, 
     e.TotalBytesToReceive, 
     e.ProgressPercentage); 
} 
+0

제안 해 주셔서 감사 드리지만 애플리케이션에서 비동기 다운로드를 허용하지 않습니다. 동기식 다운로드에서보고 진행 상황을 처리 할 방법을 찾아야합니다. –

+1

'응용 프로그램에서 비동기 다운로드를 허용하지 않음'이라는 의미를 명확히 할 수 있습니까? 귀하의 응용 프로그램은 이것을 어떻게 막을까요? –

+0

내 응용 프로그램은 여러 파일을 다운로드해야하며 동시에 한 번에 하나씩 동기화해야합니다. 이는 단순히 작업 요청입니다. 처음에는이 작업을 수행하기 위해 동기식 다운로드 인 webclient.DownloadFile()을 사용하고 있었지만 진행 상황을보고해야하므로 청크보고를 위해 webClient.OpenRead()를 사용하려고 생각했습니다. –

3

당신은 당신의 while 루프와 라인의 끝에 세미콜론이있다. 나는 그것이 받아 들여질 때까지 받아 들여진 대답이 옳은지에 관해서는 매우 혼란 스러웠다.

관련 문제