| 1 | // Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information. |
| 2 | |
| 3 | namespace WixToolset.Core.Native |
| 4 | { |
| 5 | using System; |
| 6 | using System.IO; |
| 7 | using System.Reflection; |
| 8 | using System.Text; |
| 9 | |
| 10 | internal static class AssemblyExtensions |
| 11 | { |
| 12 | internal static FindAssemblyRelativeFileResult FindFileRelativeToAssembly(this Assembly assembly, string relativePath, bool searchNativeDllDirectories) |
| 13 | { |
| 14 | // First try using the Assembly.Location. This works in almost all cases with |
| 15 | // no side-effects. |
| 16 | var path = Path.Combine(Path.GetDirectoryName(assembly.Location), relativePath); |
| 17 | var possiblePaths = new StringBuilder(path); |
| 18 | |
| 19 | var found = File.Exists(path); |
| 20 | if (!found) |
| 21 | { |
| 22 | // Fallback to the Assembly.CodeBase to handle "shadow copy" scenarios (like unit tests) but |
| 23 | // only check codebase if it is different from the Assembly.Location path. |
| 24 | var codebase = Path.Combine(Path.GetDirectoryName(new Uri(assembly.CodeBase).LocalPath), relativePath); |
| 25 | |
| 26 | if (!codebase.Equals(path, StringComparison.OrdinalIgnoreCase)) |
| 27 | { |
| 28 | path = codebase; |
| 29 | possiblePaths.Append(Path.PathSeparator + path); |
| 30 | |
| 31 | found = File.Exists(path); |
| 32 | } |
| 33 | |
| 34 | if (!found && searchNativeDllDirectories && AppContext.GetData("NATIVE_DLL_SEARCH_DIRECTORIES") is string searchDirectoriesString) |
| 35 | { |
| 36 | // If instructed to search native DLL search directories, try to find our file there. |
| 37 | possiblePaths.Append(Path.PathSeparator + searchDirectoriesString); |
| 38 | |
| 39 | var searchDirectories = searchDirectoriesString?.Split(Path.PathSeparator); |
| 40 | foreach (var directoryPath in searchDirectories) |
| 41 | { |
| 42 | var possiblePath = Path.Combine(directoryPath, relativePath); |
| 43 | if (File.Exists(possiblePath)) |
| 44 | { |
| 45 | path = possiblePath; |
| 46 | found = true; |
| 47 | break; |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | return new FindAssemblyRelativeFileResult |
| 54 | { |
| 55 | Found = found, |
| 56 | Path = found ? path : null, |
| 57 | PossiblePaths = possiblePaths.ToString() |
| 58 | }; |
| 59 | } |
| 60 | |
| 61 | internal class FindAssemblyRelativeFileResult |
| 62 | { |
| 63 | public bool Found { get; set; } |
| 64 | |
| 65 | public string Path { get; set; } |
| 66 | |
| 67 | public string PossiblePaths { get; set; } |
| 68 | } |
| 69 | } |
| 70 | } |