跳过循环元素

时间:2014-06-18 08:09:53

标签: c# loops

您好我有一个代码:

for (int z = 0; z <= db - 1; z++)
{

    string title = dataGridView1.Rows[z].Cells[2].Value.ToString();
    string postContent = dataGridView1.Rows[z].Cells[0].Value.ToString();
    string tags = dataGridView1.Rows[z].Cells[3].Value.ToString();
    string categ = textBox2.Text.ToString();
    string img = dataGridView1.Rows[z].Cells[1].Value.ToString();

    postToWordpress(title, postContent, tags, img);

}

这里的img是一个链接。该程序从此链接下载此图像,并在上传后。

public void postToWordpress(string title, string postContent, string tags, string img)

string localFilename = @"f:\bizt\tofile.jpg";
using (WebClient client = new WebClient())

try

{
    client.DownloadFile(img, localFilename);
}

catch (Exception)
{
    MessageBox.Show("There was a problem downloading the file");
}

我的问题是下一个问题。我在这一行中有更多1000个链接,有些被破坏或找不到。而这一点我的计划正在停止。

我的问题。我想要一个简单的跳过解决方案,当链接断开或程序无法下载图像时,不要发布,只需跳到下一个。

2 个答案:

答案 0 :(得分:1)

你必须使用下面提到的代码

for (int i = 0; i < length; i++)
{
    try
    {
        string img = dataGridView1.Rows[i].Cells[1].Value.ToString();
        using (WebClient client = new WebClient())
        {
            client.DownloadFile(img, localFilename);
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    } 
}

在这种情况下,如果你有任何异常,那么它将不会停止,for循环它将采取下一个项目。

答案 1 :(得分:0)

要跳过当前循环,您可以选择使用continue

你可以在catch块中使用它来抛出一些异常。

像这样的东西

try
{
   client.DownloadFile(img, localFilename);
}
catch (Exception)
{
   MessageBox.Show("There was a problem downloading the file");
   continue; // terminate current loop...
}

退出当前循环,然后开始下一个循环。

相关问题