简体   繁体   中英

How do I break out of a loop sequence only for one item of the loop, continuing to loop the other items?

I have a loop (see below). If I enter any of the catch blocks, I want to end the loop for the item I'm looping at the moment (I have an array of file paths).

Say the item is file = "C:\\test.txt"

When looping this file (C:\\test.txt), if something goes wrong, I want to halt the loop for this file BUT continue the foreach for the other files in the array finalFiles.

Is this possible?

foreach (string file in finalFiles)
{
                if (file.Contains(".tiff") == true)
                {
                    PolicyNumber = Path.GetFileName(file).Split('_')[0];
                    basePolicyNumber = PolicyNumber.Remove(PolicyNumber.Length - 2);
                    basePolicyNumber = basePolicyNumber + "00";

                    finalPolicyName = Path.GetFileName(file);

                    try
                    {
                        PolicyUUID = Transporter.GetPolicyUUID(AppVars.pxCentralRootURL, basePolicyNumber);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error getting UUID from policy online!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        uploadToPxCentralWorker.ReportProgress(0);
                    }

                    ixLibrarySourceFileURL = AppVars.ixLibraryPolicyAttachmentsURL + finalPolicyName;

                    try
                    {
                        Transporter.UploadFileToixLibrary(AppVars.ixLibraryPolicyAttachmentsURL, file);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        uploadToPxCentralWorker.ReportProgress(0);
                        error = 1;
                    }
}

Use the "continue" keyword for these situations.

MSDN link to the usage is here.

Try the continue keyword . It will continue the loop at the next iteration.

You can use continue keyword :

foreach (string file in finalFiles)
{
   if(bad condition)
    continue;
}

You can use the continue statment.

Continue Statment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM