How to check downloaded files Selenium WebDriver?
I found the solution with following source code:
string currentPage = Browser.Current.Url;
string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string downloadPath = Path.Combine(userPath, "Downloads");
DirectoryInfo dirInfo = new DirectoryInfo(downloadPath);
if (!dirInfo.Exists)
{
dirInfo.Create();
}
int directoryFiles = dirInfo.EnumerateFiles().Count();
string elementXpath = "//div[@id='myDiv']/div/div/div[@class='atalhos']/a[1]";
bool isFirefox = (Browser.Current as FirefoxDriver) != null;
bool isChrome = (Browser.Current as ChromeDriver) != null;
IWebDriver browserDriver = null;
if (isChrome)
{
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.AddUserProfilePreference("download.default_directory", downloadPath);
chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");
browserDriver = new ChromeDriver(chromeOptions);
}
else if (isFirefox)
{
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("browser.download.folderList", 2);
profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
browserDriver = new FirefoxDriver(profile);
}
browserDriver.Navigate().GoToUrl(currentPage);
WebDriverWait wait = new WebDriverWait(browserDriver, TimeSpan.FromSeconds(15));
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath(elementXpath)));
IWebElement elemento = browserDriver.FindElement(By.XPath(elementXpath));
elemento.Click();
Thread.Sleep(7000);
dirInfo = new DirectoryInfo(downloadPath);
int currentFiles = dirInfo.EnumerateFiles().Count();
Assert.Greater(currentFiles, directoryFiles);