user3715465
user3715465

Reputation: 29

Skip the element of the loop

Hello I have got a code:

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);

}

Here the img is a link. The program download this image from this link, and after upload.

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");
}

My problem is the next. I have got in this row more 1000s links, and some is broken or not found. And this point my program is stopping.

My question. I would like a simple skip solution, when the link is broken or the program can't download the image, don't post, just skip to the next.

Upvotes: 0

Views: 92

Answers (2)

Dhaval Patel
Dhaval Patel

Reputation: 7591

you have to use below mentioned code

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);
    } 
}

In this case if you got any exception then it will not stop, the for loop it will take the next item.

Upvotes: 1

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

To skip the current loop, you have the option to use continue.

You can use this inside the catch block where some exception gets thrown.

Something like this

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

Get out of the current loop, and start the next loop.

Upvotes: 0

Related Questions