CSharp WebDriver Extensions

C# WebDriver extension: Driver.TakeScreenshot

I was having a chat to a colleague this week about how Watir in Ruby is much nicer than WebDriver in other languages because it provides a lot more functionality without any work, such as screenshots, waiting etc. I hadn’t really thought about that for a while because, despite working predominantly in C#, I have a collection of WebDriver and WebElement extensions I have written which make it much easier to use.

I plan to write a series of short posts sharing a different extension method in each one.

I previously shared these:

  • IWebElement.Set(text)
  • SelectElement.SelectBySubText(subText)
  • IWebElement.FindVisibleElement(by)
  • IWebElement.VisibleElementExists(by)

Today I will share IWebDriver.TakeScreenshot(prefix). This method allows you to easily take a timestamped screenshot of what is displayed in the browser with an optional prefix to the filename.

using System;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace WebDriverExtensions
    public static class WebElementExtensions
        public static string TakeScreenshot(this IWebDriver driver, string prefix)
            var fileName = String.Format("{0}{1}{2}", prefix, DateTime.Now.ToString("HHmmss"), ".png");
            var screenShot = ((ITakesScreenshot)driver).GetScreenshot();
            screenShot.SaveAsFile(fileName, ImageFormat.Png);
            return fileName;

    public class ExtensionUnitTests
        public void TakeScreenShot()
            var driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("data:text/html,Some Text");
            var fileName = driver.TakeScreenshot("myScreenShot");