File Download at Custom Path in Selenium with C#

File Download at Custom Path in Selenium with C#

This blog will show you how to download files from websites and save them to a folder. When you use selenium to download a file from a website, the file is saved in the default download folder. Chrome options must be used to save a downloaded file to the desired location. Let's see how we can do that.

The code snippet below will download and save a file from a website. ChromeOptions() has been initialized here. In AddUserProfilePreference, download.default directory, enter the path of the directory where you want to save the downloaded file.

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Threading;
using System.Windows.Forms;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
using WebDriverManager.Helpers;

private void DownloadButton_Click(object senderEventArgs e)
{
    // Download the same version of chromedriver
    var chromeDriverPath = new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser);

    // Get a path of chromedriver
    string chromeDirectoryPath = System.IO.Path.GetDirectoryName(chromeDriverPath);
    
    // Set options and specify the folder location

    var options = new ChromeOptions();
    options.AddUserProfilePreference("download.default_directory"System.IO.Path.GetDirectoryName(Application.ExecutablePath+ @"\Download");

    // Create instance by passing the path of the chromedriver directory
    IWebDriver driver = new ChromeDriver(chromeDirectoryPathoptions);

    driver.Navigate().GoToUrl("https://localhost:7055/");
    driver.Manage().Window.Maximize();
    Thread.Sleep(2000);

    var element = driver.FindElement(By.XPath("/html/body/div/main/div/a"));
    element.Click();
}

The output of the above code snippets is shown below. As you can see, the downloaded PDF file is saved in the download folder, which is located in the bin directory.

File Download at Custom Path in Selenium with C#

I hope this helps you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

SignalR with JavaScript in ASP.NET Core MVC

Localization in ASP.NET Core MVC with Example