Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bundle/distribute Playwright with my .NET app?

I'm working on a C# desktop app (WinForms). It does some limited web scraping on the end user's behalf using Playwright. So, Playwright needs to install and work on the end user's computer when they run the app.

How can I include Playwright with the app?

like image 540
Eric Eskildsen Avatar asked Nov 17 '25 06:11

Eric Eskildsen


1 Answers

Include the .playwright directory in the zip file/installer and call Microsoft.Playwright.Program.Main from the app.

Details:

  1. In the zip file/installer that you create for your app, include the .playwright assets directory that's generated in your build target directory (example: bin/Release/net8.0/.playwright). (This directory should be automatically generated by Playwright when you build your project, provided you've added the Playwright NuGet package to your project.)
  2. In your app's code, call Microsoft.Playwright.Program.Main to install Playwright.
    using Microsoft.Playwright;
    
    // ...
    
    int exitCode = Microsoft.Playwright.Program.Main(["install", "chromium"]);
    if (exitCode != 0)
    {
        throw new Exception($"Failed to install Playwright with exit code {exitCode}.");
    }
    
    // ...
    
    var playwright = await Microsoft.Playwright.Playwright.CreateAsync();
    

Re. the .playwright directory, there's a subdirectory of it called node that has ~500MB of files. To reduce the size of your packaged app, you can delete node subdirectories that aren't for your target platform.

For example, the contents for me are:

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----           3/21/2025  8:00 AM                darwin-arm64
d----           3/21/2025  8:00 AM                darwin-x64
d----           3/21/2025  8:00 AM                linux-arm64
d----           3/21/2025  8:00 AM                linux-x64
d----           3/21/2025  8:00 AM                win32_x64
-a---          11/18/2024  1:35 PM         139053 LICENSE

I deleted all subdirectories except win32_x64, since that's my target platform.

Putting all of that together, building and packaging the app could look like this in PowerShell:

# Build in Release configuration as a self-contained app
dotnet build -c Release -r win-x64 --self-contained

# Go to the build directory
pushd bin/Release/net*/win-x64

# Remove unneeded Playwright assets
Get-ChildItem .playwright/node -Directory | ? Name -ne win32_x64 | Remove-Item -Recurse -Force

# Package the app
Compress-Archive * app.zip

# Go back to the user's working directory
popd
like image 132
Eric Eskildsen Avatar answered Nov 18 '25 18:11

Eric Eskildsen