.NET Core中使用DinkToPdf加载libwkhtmltox.dll遇DllNotFoundException
Let’s break down why you’re hitting this error and walk through the fixes step by step:
Root Cause
When running your ASP.NET app with IIS Express, Directory.GetCurrentDirectory() returns the IIS Express installation directory (C:\Program Files\IIS Express\) instead of your project’s build output folder. That’s why the runtime can’t locate libwkhtmltox.dll—it’s not copied to that system directory by default.
Step-by-Step Solutions
1. Ensure the DLL is copied to your project’s output directory
- First, place the correct architecture version of
libwkhtmltox.dll(32-bit or 64-bit, matching your project’s target platform) in a dedicated folder likelibat your project root. - In Visual Studio, right-click the DLL file → Properties → Set Copy to Output Directory to Copy always or Copy if newer. This guarantees the DLL is moved to your build output folder (e.g.,
bin/Debug/net6.0) every time you compile.
2. Use the correct base path to load the DLL
Replace Directory.GetCurrentDirectory() with AppContext.BaseDirectory—this property reliably returns your app’s base output directory, not the IIS Express system folder. Update your Startup code to:
var context = new CustomAssemblyLoadContext(); var dllPath = Path.Combine(AppContext.BaseDirectory, "libwkhtmltox.dll"); context.LoadUnmanagedLibrary(dllPath);
3. Match your project’s platform to the DLL architecture
- Right-click your project in Visual Studio → Properties → Navigate to the Build tab.
- Set Platform target to match your
libwkhtmltox.dll(x86 for 32-bit, x64 for 64-bit). Avoid using Any CPU—this can cause architecture mismatches that trigger missing DLL errors.
4. Install required dependencies
libwkhtmltox.dll depends on Microsoft Visual C++ Redistributable packages. If you still get errors after the above steps:
- Install the appropriate 32-bit or 64-bit version of the Microsoft Visual C++ Redistributable for Visual Studio (match the version compatible with your wkhtmltopdf build).
Production Deployment Note
When deploying to a production server, confirm libwkhtmltox.dll is included in your deployment package. If using publish profiles, double-check the DLL’s "Copy to Output Directory" setting ensures it’s copied to the publish directory.
内容的提问来源于stack exchange,提问作者Joseph Wambura

