From 90a44b7296756a5c284d856003c2cb1e0a7ceb99 Mon Sep 17 00:00:00 2001 From: Max Schmitt Date: Mon, 15 Apr 2024 11:57:56 +0200 Subject: [PATCH] fix: support self-contained executables --- src/Playwright/Helpers/Driver.cs | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/src/Playwright/Helpers/Driver.cs b/src/Playwright/Helpers/Driver.cs index 4da20755fa..3ac3bad489 100644 --- a/src/Playwright/Helpers/Driver.cs +++ b/src/Playwright/Helpers/Driver.cs @@ -26,6 +26,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Reflection; using System.Runtime.InteropServices; namespace Microsoft.Playwright.Helpers; @@ -48,19 +49,19 @@ internal static (string ExecutablePath, Func GetArgs) GetExecuta } if (assemblyDirectory?.Exists != true || !File.Exists(Path.Combine(assemblyDirectory.FullName, "Microsoft.Playwright.dll"))) { - string assemblyLocation; var assembly = typeof(Playwright).Assembly; -#pragma warning disable SYSLIB0012 // 'Assembly.CodeBase' is obsolete: 'Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. - if (Uri.TryCreate(assembly.CodeBase, UriKind.Absolute, out var codeBase) && codeBase.IsFile) -#pragma warning restore SYSLIB0012 // 'Assembly.CodeBase' is obsolete: 'Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. + if (TryGetCodeBase(assembly, out var codeBase) && codeBase.IsFile) { - assemblyLocation = codeBase.LocalPath; + assemblyDirectory = new FileInfo(codeBase.LocalPath).Directory; + } + else if (!string.IsNullOrEmpty(assembly.Location)) + { + assemblyDirectory = new FileInfo(assembly.Location).Directory; } else { - assemblyLocation = assembly.Location; + assemblyDirectory = new FileInfo(AppContext.BaseDirectory).Directory; } - assemblyDirectory = new FileInfo(assemblyLocation).Directory; } string executableFile; @@ -95,6 +96,22 @@ internal static (string ExecutablePath, Func GetArgs) GetExecuta throw new PlaywrightException($"Driver not found: {executableFile}"); } + private static bool TryGetCodeBase(Assembly assembly, out Uri codeBase) + { + try + { + // assembly.CodeBase might throw with: + // System.NotSupportedException: CodeBase is not supported on assemblies loaded from a single-file bundle. + Uri.TryCreate(assembly.CodeBase, UriKind.Absolute, out codeBase); + return true; + } + catch (NotSupportedException) + { + codeBase = null; + return false; + } + } + private static (string ExecutablePath, Func GetArgs) GetPath(string driversPath) { string platformId;