We need to download files for various purposes and verify the same. We will demonstrate this through a simple example. Create two empty text files namely sample_1 and sample_2 and compress them using any zip software. Store the two files at any location.

Steps to Compress the Files:

Here we are using 7-Zip (free software compression tool) to compress the files.

  1. Select the two files and right click.
  2. Hover on 7-Zip.
  3. Click on Add to sample.zip.
  4. You will get a zip file.

Download File using Selenium and Verifying

Text is not required within the files, since we simply want to confirm if we have downloaded our required files in this example.

Note:

  1. We can also use any other file type and other software compression tool can also be used.
  2. We have selected zip format for simplicity to implement our example.

Copy and store the zip file in a folder in D drive or any folder of your choice. Let the folder name be “data”.

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.

Download File using Selenium

Code Implementation

Code for implementation of the program (we use Visual Studio as our IDE). We can use Express or Community editions of Visual Studio which are freely available.

Create a solution and add a class library within it. We have created a folder (creating folder is optional) within the class library and add a class file to implement our code. Let the class file name be DownloadDemo.cs

Download File using Selenium

Download File using Selenium

Steps to Add Reference:

On the right side under projects click on References >> Add Reference

Download File using Selenium

Reference Manager dialog box opens up. Click on Assemblies. Select the references which have been highlighted. Click on OK.

Download File using Selenium

After this, declare certain variables within the class which will be used later. Google Chrome is used to implement this program. However, other browsers can be used too. Later initialize ChromeDriver.

The chromedriver.exe file has been stored in the path: C:\Program Files (x86)\chromedriver

Download File using Selenium

Note:

  1. Ensure Chrome browser is configured to download files automatically.
  2. Always use the latest chromedriver version for the most recent version of Google Chrome.

Steps to configure Google Chrome browser:

  1. Open your Google Chrome browser.
  2. At the top right, click .
  3. Click on Settings.
  4. At the bottom, click Show advanced settings link.
  5. Under the "Downloads" section, adjust your download settings:
  6. To change the default download location, click Change and select where you would like your files to be saved. This location has to be used in the code. To implement our code, we have chosen our location as C:\Users\abc\Downloads
  7. Uncheck the box "Ask where to save each file before downloading".

Download File using Selenium

This code snapshot provides some details of method Download_Demo which helps to download file and check if the file exists.  Task.Delay method is used which will create a logical delay in time till the download is completed.

Directory.Exists method checks if a specific directory is present. It accepts string as a parameter and this method is used here to check if our directory exists. It returns Boolean value. (true or false)

System.IO namespace is required for Directory.Exists method.

Download File using Selenium

This code snapshot provides details of checking the zip file and extracting the files within it.

File. Exists method requires System.IO namespace. The File. Exists method accepts string as a parameter which is used here to check if our file exists. It returns Boolean value. (true or false)

Note: There are two ways to write a path for file:

  • @" C:\Users\abc\Downloads"
  • "C:\Users\abc\Downloads"

Download File using Selenium

This code snapshot provides details of verifying files.

Directory.GetFiles method gets the files within a specific folder. The Directory.GetFiles method accepts string as a parameter.  Pass the path where the files are stored inside the method.  In the above code, files are saved in a string array (i.e. string[] fileEntries).

Download File using Selenium

Check data in Quick Watch

  1. You need to add debugger to the line of code.
  2. When you run your program (you can use NUnit to run your program), the program will halt itself at debugger.
  3. Press F10, to move to next line of code, this will ensure that the previous line of code is executed and the required data inside (in this case string [] fileEntries) will be seen.
  4. Right click on the element, for which information is required. (right click on fileEntries) (Refer Figure 11)
  5. Click on Quick Watch.

Download File using Selenium

It is seen that inside the array there are two files at index 0 and 1. However, only filename is needed.  Later, a list of string is created which will individually store only filenames.

A For loop is used to iterate through the length of array and to split the data present in array into individual elements. Iterate till the total length of the array. (Line 79)

The total length of the array represents the number of files expected; in this case we have stored two text files.

Within the For loop an array is created (i.e. string[] split) which will store the last element of the path. (i.e. the filename)

The path can be easily split using “\” character. See figure below.

Download File using Selenium

Later, add the filenames in the list. This is done by adding the last element to List listItemsName which is done with the following code.

listItemsName.Add(split.Last());

After iterating through the For loop, again, for the second time, all required elements are added in the List listItemsName, and it is seen that the list has the two items.

Download File using Selenium

List<string> originalList = new List<string> { "sample_1.txt", "sample_2.txt" };

This is the list of string which holds the elements (filenames) which we expect to be present.

Now, by comparing the number of elements in the two lists and using Contains method compare the data within the two lists. Line 85

Download File using Selenium

Later, if the result is true, pass the test and call a method to delete the test data. Else fail the test and call the method to delete the test data.

DeleteFilesAndDirectory method: In the method it is checked if the directory exists, if it exists, then delete the directory and its contents. Later also check if the zip file which has been downloaded initially is present, if it present, it is deleted.

This cleanup of data ensures that when the test is run next time it will not conflict with the existing items which were created in previous test.

Download File using Selenium

We close our browser in the end. Below you will find the complete code.

using System;
using System.Collections.Generic;
using System.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
using System.IO; // we need this namespace for working with  directories and files, a reference needs to be added for this
using System.IO.Compression;// we need this namespace for working with zip files , a reference needs to be added for this
using System.Threading.Tasks;//we need this namespace to create a logical delay in time

namespace ToolsQA.SeleniumBasics
{
    class DownloadDemo
    {
        string currentFile = string.Empty;
        static  string name = string.Empty;
        bool result = false;

        IWebDriver driver;

        [SetUp]
        public void Initialize()
        {
            driver = new ChromeDriver("C:\\Program Files (x86)\\chromedriver");
        }
                
        
        [Test]    
        public  void Download_Demo()
        {
            driver.Navigate().GoToUrl("file:///D:/data/");//browse the URL 
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
            name = driver.FindElement(By.LinkText("sample.zip")).Text; //we store the zip filename in a variable 
			driver.FindElement(By.LinkText("sample.zip")).Click();//this downloads the zip file
            Task.Delay(5000).Wait();//wait for sometime till download is completed
            string path = "C:\\Users\\abc\\Downloads";//the path of the folder where the zip file will be downloaded
            
			if (Directory.Exists(path)) //we check if the directory or folder exists
            {
                bool result = CheckFile(name); // boolean result true or false is stored after checking the zip file name
                if (result == true)
                {
                    ExtractFiles();// if the zip file is present , this method is called to extract files within the zip file
                }
                                
                else
                {
                    Assert.Fail("The file does not exist.");// if the zip file is not present, then the  test fails
                }
            }
            else
            {
                Assert.Fail("The directory or folder does not exist.");//if the directory or folder does not exist, then the test fails
            }
        }
		
		
        public bool CheckFile(string name) // the name of the zip file which is obtained, is passed in this method
        {
            currentFile = @"C:\Users\abc\Downloads\" + name + ""; // the zip filename is stored in a variable
            if (File.Exists(currentFile)) //helps to check if the zip file is present
            {
                return true; //if the zip file exists return boolean true
            }
            else
            {
                return false; // if the zip file does not exist return boolean false
            }
        }
		
		
        public void ExtractFiles()
        {
            string newExtractFolder = @"C:\Users\abc\Downloads\Extract";
            // we provide a path ( i.e. @"C:\Users\abc\Downloads\) and a name (i.e. Extract) for the new folder which will store files within the zip file
            ZipFile.ExtractToDirectory(currentFile, newExtractFolder);
            // we extract contents of the zip file to the  new folder which has been created
            VerifyFiles(newExtractFolder); //we call this method and pass the path of the folder where extracted files are stored
        }
		
		
        public void VerifyFiles(string newExtractFolder)
        {
            string[] fileEntries = Directory.GetFiles(newExtractFolder);// we obtain and store files within the "Extract" folder in an array 
            List<string> listItemsName = new List<string>();//we create a list of string which will store these  files individually
            for (int i = 0; i < fileEntries.Length; i++)
            {
                string[] split = fileEntries[i].Split('\\');
                listItemsName.Add(split.Last());
            }
            List<string> originalList = new List<string> { "sample_1.txt", "sample_2.txt"};// the files which we expect to be  present
            result = originalList.Count == listItemsName.Count && originalList.All(listItemsName.Contains);
            //compare two lists if they have the same number of items and 
            //check that all items are same, by using contains we ensure that both lists have same items, 
            //irrespective of the order(ascending or descending) of items within the lists
            if (result == true)
            {
                Console.WriteLine("The expected files are present.");
                DeleteFilesAndDirectory();//delete the test data
                Assert.Pass("The expected files are present.");
            }
            else
            {
                Console.WriteLine("The expected files are not present.");
                DeleteFilesAndDirectory();//delete the test data
                Assert.Fail("The expected files are not present.");
            }
        }
		
		
        public void DeleteFilesAndDirectory()
        {
            if (Directory.Exists(@" C:\Users\abc\Downloads\Extract"))
            {
                Directory.Delete(@" C:\Users\abc\Downloads\Extract", true);//cleanup created folder which has any content inside it.
                //true ensures that folder is deleted even if it is not empty. 
            }
            if (File.Exists(currentFile))
            {
                File.Delete(currentFile); //delete the downloaded zip file
            }
        }     
		
		
        [TearDown]
        public void End()
        {
            driver.Close();
        }
    }
}
WebElement Extensions Method
WebElement Extensions Method
Previous Article
Lakshay Sharma
I’M LAKSHAY SHARMA AND I’M A FULL-STACK TEST AUTOMATION ENGINEER. Have passed 16 years playing with automation in mammoth projects like O2 (UK), Sprint (US), TD Bank (CA), Canadian Tire (CA), NHS (UK) & ASOS(UK). Currently, I am working with RABO Bank as a Chapter Lead QA. I am passionate about designing Automation Frameworks that follow OOPS concepts and Design patterns.
Reviewers
Virender Singh's Photo
Virender Singh

Similar Articles

Feedback