Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


Download a file from a URL with Selenium in C#
You may want to use .NET/C# to download a file from a URL with Selenium to disk.
(This allows you to confirm the file downloaded to the disk matches what you expect).
Here is an extension method for the driver to do this.

Usage:
myDriver.DownloadFile(inputHref, outputPath);

Code:

/// <summary>
/// Get the driver's cookie header string.
/// </summary>
/// <param name="driver"></param>
/// <returns></returns>
static string GetCookieHeaderString(IWebDriver driver)
{
var cookies = driver.Manage().Cookies.AllCookies;
return string.Join("; ", cookies.Select(c => string.Format("{0}={1}", c.Name, c.Value)));
}

/// <summary>
/// Downloads a file from a URL to disk.
/// </summary>
/// <param name="driver"></param>
/// <param name="sourceURL"></param>
/// <param name="destinationPathAndName"></param>
public static void DownloadFile(this IWebDriver driver, string sourceURL, string destinationPathAndName)
{
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.Cookie] = GetCookieHeaderString(driver);
wc.DownloadFile(sourceURL, destinationPathAndName);
}
}

Created By: amos 3/4/2016 2:05:52 PM
Updated: 3/4/2016 2:06:02 PM


 Comments:
 > Guest 5/25/2022 1:30:02 PM
Thx!
Helped me a lot