I wrote an automation test in Selenium webdriver using C#, and one of steps requires to download a XLSX file from server. How to validate if file has downloaded successfully and get his name?
Regards
Now, open Google Chrome (we are using Google Chrome as our default browser). Copy the URL: D:\data in the URL of your browser. Once you copy the URL, you will observe that the URL is updated as “file:///D:/data/ “. You will also observe the sample file created by you in the browser.
Press Ctrl+J to view browser downloads If you double-click a file in the list, it opens or runs. You can also click a button to open the folder on your computer where the file was downloaded. In the example pictured below, a downloaded file is shown in the Firefox downloads window (called the "Library").
The most basic way of uploading files in Selenium is using the sendKeys method. It is an inbuilt feature for file upload in Selenium.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With