With Selenium, I upload the students' pictures in the folder, respectively, according to the student information in the datagridview. The program works smoothly, but it gives an error for students whose pictures are not in the folder. How can we skip students whose pictures are not in the folder?

C#
drv.SwitchTo().Window(drv.WindowHandles.ToList().Last());
for (int i = 0; i
{
var element = drv.FindElement(By.XPath("//input[@type='file']"));
return element.Displayed ? element : throw new NoSuchElementException();
});
if (filePath != null)
{
fileInput.SendKeys(filePath); // I am getting error here
SendKeys.SendWait("{Enter}");
SendKeys.SendWait("{ESC}");
}
else
{
continue;
}
}
}
catch (NoSuchElementException)
{
continue;
}
}
}
Jithu ThomasRank #437 · 5.7K reputationPosted Jan 14, 2024, 6:15 AM EST
drv.SwitchTo().Window(drv.WindowHandles.ToList().Last());
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
try
{
var val0 = dataGridView1.Rows[i].Cells[0].Value?.ToString(); // students’ numbers
if (!string.IsNullOrEmpty(val0))
{
string jpgname = val0; // Assuming jpgname is derived from the student number
string filePath = Path.Combine(Application.StartupPath, "resimler", jpgname + ".jpg");
// Check if the file exists
if (File.Exists(filePath))
{
Actions actions = new Actions(drv);
IWebElement uploadPhotoBtn = drv.FindElement(By.XPath("//*[@id='flResimSec']"));
Thread.Sleep(3000);
WebDriverWait wait = new WebDriverWait(drv, TimeSpan.FromSeconds(10));
IWebElement fileInput = wait.Until(drv =>
{
var element = drv.FindElement(By.XPath("//input[@type='file']"));
return element.Displayed ? element : throw new NoSuchElementException();
});
fileInput.SendKeys(filePath);
SendKeys.SendWait("{Enter}");
SendKeys.SendWait("{ESC}");
}
else
{
// File does not exist, skip this student
continue;
}
}
}
catch (NoSuchElementException)
{
// Handle NoSuchElementException if needed
continue;
}
}
Mehmet FatihRank #1,474 · 1.1K reputationPosted Jan 14, 2024, 6:38 AM EST
Thanks a lot for your help, Jithu Thomas.. Your are vry kind.