diff --git a/BuildAll.ps1 b/BuildAll.ps1 old mode 100644 new mode 100755 diff --git a/dev/UndockedRegFreeWinRT/UndockedRegFreeWinRT-AutoInitializer.cs b/dev/UndockedRegFreeWinRT/UndockedRegFreeWinRT-AutoInitializer.cs index 2e07c542..70d0c100 100644 --- a/dev/UndockedRegFreeWinRT/UndockedRegFreeWinRT-AutoInitializer.cs +++ b/dev/UndockedRegFreeWinRT/UndockedRegFreeWinRT-AutoInitializer.cs @@ -16,6 +16,11 @@ internal static class NativeMethods { [DllImport("Microsoft.WindowsAppRuntime.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern int WindowsAppRuntime_EnsureIsLoaded(); + + // Direct Win32 API call to set environment variable as fallback + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetEnvironmentVariableW(string name, string value); } class AutoInitialize @@ -24,7 +29,37 @@ class AutoInitialize internal static void AccessWindowsAppSDK() { // Set base directory env var for PublishSingleFile support (referenced by SxS redirection) - Environment.SetEnvironmentVariable("MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY", AppContext.BaseDirectory); + try + { + Environment.SetEnvironmentVariable("MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY", AppContext.BaseDirectory); + } + catch (System.MissingMethodException) + { + // Fallback: Use direct Win32 API call when Environment.SetEnvironmentVariable is not available + // This can happen in trimmed environments (PublishTrimmed=true) + try + { + NativeMethods.SetEnvironmentVariableW("MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY", AppContext.BaseDirectory); + } + catch + { + // Ignore failures in the fallback path - continue execution + // as it's better than crashing the application + } + } + catch (System.Exception) + { + // Catch any other unexpected exceptions to ensure application doesn't crash + // Try the fallback mechanism + try + { + NativeMethods.SetEnvironmentVariableW("MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY", AppContext.BaseDirectory); + } + catch + { + // Ignore failures in the fallback path + } + } // No error handling needed as the target function does nothing (just {return S_OK}). // It's the act of calling the function causing the DllImport to load the DLL that