Last updated: February 5, 2025

<span aria-hidden="true" id="take-screenshots-of-webpages-or-html-files-in-net-c"></span>

# Take screenshots of webpages or HTML files in .Net (C#)

![Tim Koschützki](/assets/images/teammates/avatar-tim-kos-1.jpg?dpl=dpl_B2d4XACVUtA1h8m6kRxZhWsda77Q)

#### Tim Koschützki

Co-founder · Berlin, Germany · Show bio

[](https://x.com/tim%5Fkos)[](https://github.com/tim-kos)

Capturing screenshots of webpages programmatically is a valuable capability for automated testing, documentation, and monitoring. In this guide, we will explore how to capture screenshots of webpages and HTML files using .NET (C#).

<span aria-hidden="true" id="prerequisites"></span>

## Prerequisites

To follow along with this tutorial, you will need:

* .NET 6.0 or later
* Visual Studio 2022 or Visual Studio Code
* NuGet Package Manager

<span aria-hidden="true" id="using-selenium-webdriver"></span>

## Using Selenium WebDriver

Selenium WebDriver is a powerful tool for browser automation that includes screenshot capabilities. First, install the required NuGet packages:

```powershell
Install-Package Selenium.WebDriver -Version 4.28.0
Install-Package WebDriverManager -Version 2.17.1

```

Below is an updated example demonstrating how to capture a full-page screenshot with proper error handling using the Selenium 4 `TakeScreenshot()` extension method:

```csharp
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Support.Extensions;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;

public class ScreenshotCapture
{
    public static void CaptureWebpage(string url, string outputPath)
    {
        try
        {
            new DriverManager().SetUpDriver(new ChromeConfig());
            var options = new ChromeOptions();
            options.AddArgument("--headless=new");

            using (var driver = new ChromeDriver(options))
            {
                driver.Navigate().GoToUrl(url);

                // Wait until the page is fully loaded
                var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
                wait.Until(d => ((IJavaScriptExecutor)d)
                    .ExecuteScript("return document.readyState").Equals("complete"));

                // Adjust the window size to capture the full page height
                var totalHeight = (long)((IJavaScriptExecutor)driver)
                    .ExecuteScript("return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);");
                driver.Manage().Window.Size = new System.Drawing.Size(1920, (int)totalHeight);

                var screenshot = driver.TakeScreenshot();
                screenshot.SaveAsFile(outputPath, ScreenshotImageFormat.Png);
            }
        }
        catch (WebDriverException ex)
        {
            throw new Exception($"Failed to capture screenshot: {ex.Message}", ex);
        }
    }
}

```

<span aria-hidden="true" id="browser-compatibility"></span>

## Browser compatibility

The code examples in this guide are compatible with:

* Chrome: Version 115+
* Firefox: Version 115+
* Edge: Version 115+

###### Note

For Chrome version 115 and above, the ChromeDriver installation process is handled automatically by WebDriverManager.

<span aria-hidden="true" id="capturing-local-html-files"></span>

## Capturing local HTML files

To capture screenshots of local HTML files, use the `file://` protocol with proper error handling:

```csharp
using System;
using System.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Support.Extensions;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;

public static void CaptureLocalHtml(string htmlFilePath, string outputPath)
{
    try
    {
        var absolutePath = Path.GetFullPath(htmlFilePath);
        var fileUri = new Uri(absolutePath).AbsoluteUri;

        new DriverManager().SetUpDriver(new ChromeConfig());
        var options = new ChromeOptions();
        options.AddArgument("--headless=new");

        using (var driver = new ChromeDriver(options))
        {
            driver.Navigate().GoToUrl(fileUri);

            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            wait.Until(d => ((IJavaScriptExecutor)d)
                .ExecuteScript("return document.readyState").Equals("complete"));

            var screenshot = driver.TakeScreenshot();
            screenshot.SaveAsFile(outputPath, ScreenshotImageFormat.Png);
        }
    }
    catch (Exception ex)
    {
        throw new Exception($"Failed to capture local HTML: {ex.Message}", ex);
    }
}

```

<span aria-hidden="true" id="handling-dynamic-content"></span>

## Handling dynamic content

Modern web applications often include dynamic content that requires additional time to load:

```csharp
using System;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Support.Extensions;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;

public static void CaptureDynamicWebpage(string url, string outputPath)
{
    try
    {
        new DriverManager().SetUpDriver(new ChromeConfig());
        var options = new ChromeOptions();
        options.AddArgument("--headless=new");

        using (var driver = new ChromeDriver(options))
        {
            driver.Navigate().GoToUrl(url);

            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            // Wait for a specific element to ensure dynamic content is loaded
            wait.Until(d => d.FindElement(By.Id("content-loaded")));

            // Additional wait for any animations
            Thread.Sleep(1000);

            driver.Manage().Window.Size = new System.Drawing.Size(1920, 1080);

            var screenshot = driver.TakeScreenshot();
            screenshot.SaveAsFile(outputPath, ScreenshotImageFormat.Png);
        }
    }
    catch (WebDriverTimeoutException ex)
    {
        throw new Exception("Timeout waiting for dynamic content to load", ex);
    }
}

```

<span aria-hidden="true" id="managing-screenshot-storage"></span>

## Managing screenshot storage

To keep your screenshots organized and manage storage efficiently:

```csharp
using System;
using System.IO;

public class ScreenshotManager
{
    private readonly string _baseDirectory;

    public ScreenshotManager(string baseDirectory)
    {
        _baseDirectory = baseDirectory;
        Directory.CreateDirectory(_baseDirectory);
    }

    public string SaveScreenshot(byte[] screenshotBytes, string prefix = "")
    {
        var fileName = $"{prefix}screenshot_{DateTime.Now:yyyyMMdd_HHmmss}.png";
        var filePath = Path.Combine(_baseDirectory, fileName);
        File.WriteAllBytes(filePath, screenshotBytes);
        return filePath;
    }

    public void CleanupOldScreenshots(int daysToKeep = 7)
    {
        var cutoffDate = DateTime.Now.AddDays(-daysToKeep);
        var files = Directory.GetFiles(_baseDirectory, "*.png");
        foreach (var file in files)
        {
            if (File.GetCreationTime(file) < cutoffDate)
            {
                File.Delete(file);
            }
        }
    }
}

```

<span aria-hidden="true" id="handling-different-screen-sizes"></span>

## Handling different screen sizes

For responsive design testing, capture screenshots at various viewport sizes:

```csharp
using System;
using System.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Support.Extensions;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;

public static void CaptureResponsiveScreenshots(string url, string outputDirectory)
{
    try
    {
        new DriverManager().SetUpDriver(new ChromeConfig());
        var viewports = new[]
        {
            new { Width = 375, Height = 667, Name = "mobile" },
            new { Width = 768, Height = 1024, Name = "tablet" },
            new { Width = 1920, Height = 1080, Name = "desktop" }
        };

        var options = new ChromeOptions();
        options.AddArgument("--headless=new");

        using (var driver = new ChromeDriver(options))
        {
            foreach (var viewport in viewports)
            {
                driver.Manage().Window.Size = new System.Drawing.Size(viewport.Width, viewport.Height);
                driver.Navigate().GoToUrl(url);

                var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(2));
                wait.Until(d => ((IJavaScriptExecutor)d)
                    .ExecuteScript("return document.readyState").Equals("complete"));

                var screenshot = driver.TakeScreenshot();
                var outputPath = Path.Combine(outputDirectory,
                    $"{viewport.Name}_{DateTime.Now:yyyyMMdd_HHmmss}.png");
                screenshot.SaveAsFile(outputPath, ScreenshotImageFormat.Png);
            }
        }
    }
    catch (Exception ex)
    {
        throw new Exception($"Failed to capture responsive screenshots: {ex.Message}", ex);
    }
}

```

<span aria-hidden="true" id="conclusion"></span>

## Conclusion

This guide demonstrates various approaches to capturing webpage screenshots programmatically in .NET, from static pages to dynamic content and responsive designs. The examples include detailed error handling, browser compatibility considerations, and best practices for managing screenshot storage.

\#csharp#dotnet#selenium#document-processing-service

### 👩‍💻 Join 20k+ developers

Sign up for our [monthly newsletter](/newsletters.md) to receive direct links to 3 exclusive tech — and 2 product updates. No less, no more.

Your email:

Get access

## File uploading and encoding. Made simple.

Transloadit streamlines file handling for developers, trusted by brands like Coursera and The New York Times. We’re known for a reliable API, top-notch support, and a strong commitment to open source, with projects like [Uppy⁠](https://uppy.io) and [Tus⁠](https://tus.io) setting standards in file processing.

[Sign up](/c/)[Book a Demo](https://survey.typeform.com/to/kRg47Xi5)

No credit card needed · 5 GB included in the free plan

Cancel anytime
