2012-08-19 50 views
0

我試圖找出以下問題,但我無法做到這一點,因爲我剛剛開始編程一個月前。從列表框中的項目下載多個文件

我有20個項目列表框:

private void loadDownloadXMLListBox() 
{ 
    var items = new[] { "BARC", "DEV", "DOM", "EZJ", "GFS", 
         "IHG", "JD.", "LAD", "LLOY", "MRW", 
         "NXT", "OCDO", "RBS", "SMWH", "SPD", 
         "STAN", "SYR", "TALK", "TSCO", "WMH" }; 
    foreach (var item in items) listDownloadXML.Items.Add(item); 

    listDownloadXML.SelectedIndex = -1; 
} 

這是我從網站上下載一個選定的文件代碼:

private void btnDownloadXML_Click(object sender, EventArgs e) 
{ 
    using (WebClient client = new WebClient()) 
    { 
     client.DownloadFile("http://www.lse.co.uk/chat/" + listDownloadXML.SelectedItem, 
                @"..\..\sharePriceXML\" + 
             listDownloadXML.SelectedItem + ".xml"); 
    } 
    MessageBox.Show("Download Completed! File has been placed in the folder sharePriceXML!"); 
} 

我想點擊一個按鈕「下載所有「那麼,網站上的所有20個項目都將被下載。我是否可以知道如何循環訪問列表框中的20個項目並將它們全部下載到文件夾中而不選擇項目?謝謝。

回答

2
foreach (var item in listDownloadXML.Items) 
{ 
    //... your code to download "item". 
} 
+0

謝謝你的幫助。 :) – Shyuan 2012-08-19 15:38:21

1

您可以通過外在的下載單個文件功能集成到一個單獨的,可重用的方法來啓動:

public void DownloadFile(string item) 
{ 
    using (var client = new WebClient()) 
    { 
     client.DownloadFile(
      "http://www.lse.co.uk/chat/" + item, 
      @"..\..\sharePriceXML\" + item + ".xml" 
     ); 
    } 
    MessageBox.Show("Download Completed! File has been placed in the folder sharePriceXML!"); 
} 

然後:

private void btnDownloadXML_Click(object sender, EventArgs e) 
{ 
    DownloadFile((string)listDownloadXML.SelectedItem); 
} 

和現在你對多個文件的問題=>您使用循環併爲列表框中的每個元素調用DownloadFile方法:

foreach (string item in listDownloadXML.Items) 
{ 
    DownloadFile(item); 
} 
+0

謝謝你的幫助:) – Shyuan 2012-08-19 15:39:16

相關問題