2014-06-18 116 views
0

你好,我有我的代碼:跳過循環的元素

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個鏈接,並且有些被破壞或未找到。這一點我的計劃正在停止。

我的問題。我想要一個簡單的跳過解決方案,當鏈接中斷或程序無法下載圖像時,請勿發佈,直接跳到下一個。

+7

使用'continue'跳過循環的當前迭代 –

+2

第一個和第二個代碼塊之間的關係是什麼? –

回答

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循環將採取的下一個項目。

0

要跳過當前循環,您可以選擇使用continue

你可以在catch塊內部使用這個引發一些異常的地方。

像這樣的事情

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

擺脫目前的循環,然後開始下一個循環。

+0

或者,你可以設置圍繞調用postToWordpress的循環中的try/catch來捕獲可能引發的任何錯誤。 – Eterm