我试图搞清楚以下问题,但我无法做到这一点,因为我刚开始编程一个月前。
我有一个包含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个项目并将它们全部下载到文件夹而不选择项目吗?谢谢。
答案 0 :(得分:2)
foreach (var item in listDownloadXML.Items)
{
//... your code to download "item".
}
答案 1 :(得分: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);
}