Tech News

Embed Local HTML File Using Edge WebView2 API in WinForms

Learn how to embed a local HTML file in a C# WinForms app using the new Edge WebView2 1.0.1836.0 API. Step-by-step guide for developers.

IMTechy
IMTechy
29 Oct 2026
8 min read
58 views
Embed Local HTML File Using Edge WebView2 API in WinForms

Look, you’ve probably stared at a blank WinForms form wondering why the UI feels stuck in the 2000s. I felt that same pain when I tried to ship a quick settings pane for an internal tool and ended up with a clunky WebBrowser control that refused to render modern CSS. Then Microsoft dropped WebView2 1.0.1836.0, and my life got a lot easier if you know how to wrangle it.


Edge WebView2 & WinForms: quick intro

WebView2 is basically a thin wrapper around the Chromium engine that ships with Edge. It lets you embed a full‑blown browser inside any WinForms or WPF window. No more “this HTML looks weird in IE”. The API surface is tiny, but the version number matters a lot. The 1.0.1836.0 build fixed a handful of crashes that used to bite me at 2 am.


Prerequisites: Tools & Environment Setup

  • Visual Studio 2022 (Community is fine).

  • Windows 10 1903+ or Windows 11.

  • .NET Framework 4.7.2+ or .NET 6+ if you prefer the newer SDK.

I keep a tiny checklist in a markdown file so I don’t forget anything. It looks like this:

- [x] VS2022 installed
- [x] .NET 4.7.2 SDK
- [x] Edge (Chromium) up to date
- [x] WebView2 Runtime installed

If you’re on a CI server, you can drop the runtime via chocolatey:

choco install microsoft-edge-webview2 -y

Installing WebView2 Runtime & SDK

First, grab the Evergreen Runtime from Microsoft’s site. It auto‑updates, which is why I love it. The installer will pop a UI that says “Installing…”. Let it finish.

Next, add the NuGet package to your project:

Install-Package Microsoft.Web.WebView2 -Version 1.0.1836.0

What NOT to do – hard‑code the DLL path:

// Wrong! This will break on any machine that doesn’t have the DLL in that folder.
var env = await CoreWebView2Environment.CreateAsync(@"C:\Program Files (x86)\Microsoft\EdgeWebView\Application\92.0.902.55");

Fix – let the runtime locate itself:

var env = await CoreWebView2Environment.CreateAsync(); // Let Evergreen do its thing
webView2.CoreWebView2Environment = env;

That line saved me from a nasty “Failed to find WebView2 runtime” error that showed up in the Output window.


Creating the WinForms Project

Open VS, hit File → New → Project, pick Windows Forms App (.NET Framework), name it LocalHtmlViewer, and click Create. I always tick Enable NuGet package restore otherwise the build will choke on missing references.

Add a new folder called Assets and drop index.html there. The folder will be copied to the output directory later.


Adding the WebView2 Control

Drag the WebView2 component from the toolbox onto Form1. Resize it to fill the form. VS will generate this designer code:

// Wrong: the control is never initialized because the designer file got corrupted.
private Microsoft.Web.WebView2.WinForms.WebView2 webView2;

public Form1()
{
    InitializeComponent(); // Missing webView2 = new WebView2();
}

Fix – let the designer do its job, or manually instantiate:

private Microsoft.Web.WebView2.WinForms.WebView2 webView2;

public Form1()
{
    InitializeComponent();
    webView2 = new Microsoft.Web.WebView2.WinForms.WebView2();
    webView2.Dock = DockStyle.Fill;
    this.Controls.Add(webView2);
}

Now the control lives happily inside the form.


Loading a Local HTML File

The trick is to use a file:// URI that points to the compiled Assets folder. First, set the file to Copy Always in its properties.

private async void Form1_Load(object sender, EventArgs e)
{
    // WRONG: using a relative path without converting to a URI.
    webView2.Source = new Uri("Assets\\index.html");
}

That line throws System.UriFormatException: Invalid URI: The format of the URI could not be determined.

Correct version:

private async void Form1_Load(object sender, EventArgs e)
{
    var htmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets", "index.html");
    var uri = new Uri(htmlPath);
    await webView2.EnsureCoreWebView2Async();
    webView2.CoreWebView2.Navigate(uri.AbsoluteUri);
}

If you run the app now, you’ll see your local page rendered with Chromium fidelity. No more “This page is broken in IE”.


Handling Navigation & Events

You’ll probably want to intercept clicks or block navigation to external sites. Hook the NavigationStarting event:

// WRONG: forgetting to subscribe, so the handler never runs.
webView2.NavigationStarting += OnNavigationStarting;

// Fix – make sure you subscribe *after* EnsureCoreWebView2Async
private async void Form1_Load(object sender, EventArgs e)
{
    await webView2.EnsureCoreWebView2Async();
    webView2.NavigationStarting += OnNavigationStarting;
    // ... navigate as before
}

private void OnNavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e)
{
    if (e.Uri.StartsWith("http"))
    {
        // Block external links
        e.Cancel = true;
        MessageBox.Show("External links are disabled.", "Notice");
    }
}

The e.Cancel = true line stops the navigation dead in its tracks. I once missed that and my app opened a phishing site in a hidden window tbh, that was a close call.


Advanced: Passing Data between C# and JavaScript

WebView2 lets you execute JS from C# and vice‑versa. Let’s start simple: send a JSON payload to the page.

// WRONG: trying to pass a raw C# object.
webView2.CoreWebView2.PostWebMessageAsJson(myObject);

That throws ArgumentException: JSON string expected. The fix is to serialize first:

using System.Text.Json;

var payload = new { user = "Alice", role = "admin" };
var json = JsonSerializer.Serialize(payload);
webView2.CoreWebView2.PostWebMessageAsJson(json);

On the JS side, listen for the message:

<script>
window.chrome.webview.addEventListener('message', event => {
    console.log('Received from C#:', event.data);
});
</script>

If you need to call C# from JS, expose a host object:

// Register a host object named "bridge"
webView2.CoreWebView2.AddHostObjectToScript("bridge", new Bridge());

public class Bridge
{
    public void ShowMessage(string msg)
    {
        MessageBox.Show(msg, "From JS");
    }
}

And in your HTML:

<button onclick="window.chrome.webview.hostObjects.bridge.ShowMessage('Hello from JS')">
    Click me
</button>

Real‑world scenario: I used this pattern to surface a live log viewer inside a WinForms admin console. The backend C# pushed log entries as JSON, the front‑end displayed them instantly with a tiny React bundle. No extra sockets needed.


Common Pitfalls & Debugging Tips

  • Runtime not found – you’ll see WebView2RuntimeNotFoundException. Verify the Evergreen installer ran, or ship the Fixed‑Version runtime with your installer.

  • File path issues – Windows path separators can bite you. Use Path.Combine and Uri.AbsoluteUri.

  • Cross‑origin restrictions – If your HTML loads local resources (CSS, images), make sure they’re also in the output folder. Otherwise you’ll get “Failed to load resource: net::ERR_FILE_NOT_FOUND”.

  • Event ordering – NavigationCompleted fires before the DOM is ready. Use CoreWebView2.DOMContentLoaded if you need to manipulate the page after load.

When I was stuck on a mysterious “Script error: Object expected” message, I opened the WebView2 DevTools (press F12) and saw the console complaining about a missing fetch polyfill. Turning on Remote Debugging via:

await webView2.EnsureCoreWebView2Async();
webView2.CoreWebView2.OpenDevToolsWindow();

gave me the same experience as Chrome DevTools. If you’re hunting a phantom crash, check out the Rust Segmentation Fault guide I once read: Rust Segmentation Fault in Unsafe Blocks – Debugging Guide. The systematic approach there helped me isolate the problem to a bad COM interop call.


Real‑World Use Cases & Analogies

Think of WebView2 as a window you can stick into any legacy desktop app, just like you’d embed a TV screen into a kitchen cabinet. It lets you reuse existing web assets without rewriting them in WinForms controls.

  • Internal dashboards – Load an Angular admin panel inside a corporate tool, keep the same SSO token, avoid a second login prompt.

  • Help system – Serve a static HTML manual with searchable content, no need for a separate installer.

  • Hybrid games – Some studios embed a web‑based UI for inventory screens while the core game runs in DirectX.

If you ever built a voice‑controlled smart mirror (I did, see the blog post on that), you already know how to bridge a UI layer with hardware. Swap the mirror’s browser for WebView2, and you’ve got a Windows kiosk ready for touch and voice.


Conclusion & Next Steps

I won’t sugarcoat it—WebView2 has quirks, but the payoff is huge. You get modern HTML/CSS/JS inside a WinForms app with a few lines of code. The key takeaways:

  • Install the Evergreen runtime and the matching NuGet package.

  • Use EnsureCoreWebView2Async before touching the control.

  • Convert file paths to proper URIs to avoid UriFormatException.

  • Leverage PostWebMessageAsJson and host objects for C# ↔ JS communication.

From here, you can explore WebView2’s virtual host mapping to serve resources from embedded resources, or experiment with WebView2’s PDF printing capabilities. The sky’s the limit.


Quick Summary

Honestly, the biggest win for me was ditching the ancient WebBrowser control and finally getting my UI to look like the modern web. A few minutes of setup, a couple of async calls, and you’re ready to roll out a polished, Chromium‑powered experience inside any WinForms form. Keep the runtime up to date, watch out for path bugs, and don’t forget to open DevTools when things go sideways. You’ll thank yourself when the next release ships without that “blank page” nightmare.


FAQs

Q1: Why does my app crash with WebView2RuntimeNotFoundException even though Edge is installed?
A: Edge’s Chromium engine and the WebView2 runtime are separate. Install the Evergreen runtime from Microsoft’s site or bundle the Fixed‑Version runtime with your installer.

Q2: Can I load a local HTML file that references other local assets (CSS, images)?
A: Yes, but all assets must be copied to the output folder and referenced with relative paths. Use Path.Combine to build the absolute file URI before navigating.

Q3: How do I call a C# method from JavaScript without exposing the whole object?
A: Register a minimal host object with only the methods you need via AddHostObjectToScript. Keep the class public sealed and mark methods you want to expose with [System.Runtime.InteropServices.ComVisible(true)].

Q4: Is there a way to debug JavaScript errors inside WebView2?
A: Absolutely. Call webView2.CoreWebView2.OpenDevToolsWindow() after EnsureCoreWebView2Async. It opens the Chromium DevTools where you can view console logs, network requests, and breakpoints.

Q5: My HTML page uses fetch to call a local API, but I get CORS errors. What now?
A: Since the page is loaded via file://, the browser treats it as a different origin. You can either enable WebView2’s virtual host mapping to serve the page over http://app.local/ or add the appropriate CORS headers on the API side.


Tags:Edge WebView2WinFormsC#local HTMLAPI tutorial
Share this article:
Sameer Singh

Written by

Sameer Singh

Founder & Technology Writer

Expertise in AI, Web Development & Cybersecurity. Passionate about making complex technology accessible and actionable for everyone.