Reputation: 823
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
Upvotes: 10
Views: 28267
Reputation: 1
In the below code, i have taken the list of excel files in the download folder. If you have only one file then use file.name property or if you have multiple files try the below code.
private static string GetDownloadedFileName()
{
var fileName = ConfigurationManager.AppSettings["excelName"].ToString();
string pathUser=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload = Path.Combine(pathUser, "Downloads");
DirectoryInfo downloadDir = new DirectoryInfo(pathDownload);
FileInfo[] files = downloadDir.GetFiles("*.xls");
var file = files.Where(x => x.Name.Replace(" ", "") == fileName + ".xls").FirstOrDefault();
fileName = file.FullName;
return fileName;
}
Upvotes: 0
Reputation: 823
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);
Upvotes: 8