2013-11-25 41 views
0

您好,我有下面的C#代碼下載按鈕點擊圖像。下載圖像使用webclient不工作

private void DownloadCover() 
{ 
    try 
    { 
     string SaveFileLocation = AppDomain.CurrentDomain.BaseDirectory + "\\data\\covers\\test.jpg" ; 
     WebClient webClient = new WebClient(); 
     string cURL = "http://upload.wikimedia.org/wikipedia/commons/4/45/Right-facing-Arrow-icon.jpg"; 
     webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted); 
     webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged); 
     webClient.DownloadFileAsync(new Uri(cURL), SaveFileLocation); 
     webClient.Dispose(); 
    } 
    catch (Exception exd) 
    { 
     ErrorLogger.LogError(exd.ToString()); 
    } 

} 

private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
{ 
    lbStatus.Text = "Downloading Cover..." + e.ProgressPercentage + "%"; 
} 

private void DownloadCompleted(object sender, AsyncCompletedEventArgs e) 
{ 
    try 
    { 
     lbStatus.Text = "Download Complete"; 
     string CoverPath = AppDomain.CurrentDomain.BaseDirectory + "\\data\\covers\\test.jpg"; 
     coverImage.Image = new Bitmap(CoverPath); 

    } 
    catch (Exception ex) 
    { 
     ErrorLogger.LogError(ex.ToString()); 
    } 
} 

private void btnDownloadImage_Click(object sender, EventArgs e) 
{ 

    DownloadCover(); 
} 

當單擊該按鈕,代碼永遠不會執行下載進度變化的處理方法DownloadProgressChanged。無論何時點擊按鈕,它立即進入DownloadComplete方法並在標籤中打印「下載完成」。我試圖下載可變大小的圖像,沒有運氣。 我不知道我的代碼有什麼問題。有人可以幫我嗎?

感謝

+0

mmmh,我不認爲你可以做你想做的。基本上,要更新你的lbstatus.Text,你需要發送一個響應給客戶端,但爲了發送響應,你需要一個請求......我從來沒有使用異步代碼服務器端,但正如我所看到的你只能用它來更新數據庫或發送郵件或任何東西,但再次發送一個響應到客戶端... –

+0

@Bartdude,更新標籤不是我的問題,代碼根本沒有下載圖像。 – WatsMyName

回答

4

異步操作完成之前不能處理Web客戶端。只需將Dispose調用放入您的Download_Complete(以及錯誤和其他),它就可以工作。

0

對不起,男士們,

我發現了這個問題。我不會刪除這個線程,因爲將來有人可能會陷入類似的愚蠢錯誤。

問題是。 test.jpg文件正在使用中,webclient無法覆蓋已經使用的文件。

感謝大家的努力。