Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Uninstaller: the first copy ends before its file goes; no system error boxes
KnifeLemondfff2d2951d4
diff --git a/src/Filee.Setup/Installation/Uninstaller.cs b/src/Filee.Setup/Installation/Uninstaller.csindex 261afd32..94bdd1e3 100644--- a/src/Filee.Setup/Installation/Uninstaller.cs+++ b/src/Filee.Setup/Installation/Uninstaller.cs@@ -21,9 +21,14 @@ public sealed class Uninstaller(SetupContext context)public static TimeSpan CleanupTimeout { get; } = TimeSpan.FromSeconds(90);/// <param name="trash">A folder outside the install folder (same volume if possible) for files still in use.</param>+ /// <param name="releaseUninstaller">+ /// Called when only uninstall.exe and the folder are left: the uninstaller that started this one from the install+ /// folder is told it worked and ends, so its uninstall.exe can be deleted (a single-file program loads parts of+ /// itself from its file while it runs: that file must not move away under it).+ /// </param>/// <returns>Files and folders that are deleted at the next restart.</returns>public IReadOnlyList<string> Run(string folder, InstallRecord record, bool deleteSettings, string trash,- IProgress<SetupProgress>? progress = null)+ IProgress<SetupProgress>? progress = null, Action? releaseUninstaller = null){folder = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));Log.Info($"Uninstalling Filee {record.Version} from {folder} ({record.Scope}); delete settings: {deleteSettings}");@@ -55,7 +60,8 @@ public sealed class Uninstaller(SetupContext context)}progress?.Report(new SetupProgress(SetupStep.Removing, 0.5));- var files = record.Files.Concat([SetupNames.InstallRecordFile, SetupNames.UninstallerExe]).Concat(SetupNames.InnoUninstallerFiles)+ var files = record.Files.Concat([SetupNames.InstallRecordFile]).Concat(SetupNames.InnoUninstallerFiles)+ .Where(f => !f.Equals(SetupNames.UninstallerExe, StringComparison.OrdinalIgnoreCase)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();for (var i = 0; i < files.Count; i++){@@ -68,6 +74,17 @@ public sealed class Uninstaller(SetupContext context)foreach (var work in Directory.EnumerateDirectories(folder, FileSwap.WorkFolderPrefix + "*"))FileSwap.DeleteTree(work, System, Log);}++ Registry.DeleteKey(hive, SetupNames.UninstallKey);+ progress?.Report(new SetupProgress(SetupStep.Removing, 0.95));+ if (deleteSettings)+ {+ Log.Info($"Deleting the settings in {context.Paths.SettingsFolder}");+ FileSwap.DeleteTree(context.Paths.SettingsFolder, System, Log);+ }++ releaseUninstaller?.Invoke();+ DeleteFile(Path.Combine(folder, SetupNames.UninstallerExe), trash, later);FileSwap.RemoveEmptyFolders(folder);try{@@ -84,14 +101,6 @@ public sealed class Uninstaller(SetupContext context)later.Add(folder);}}-- Registry.DeleteKey(hive, SetupNames.UninstallKey);- progress?.Report(new SetupProgress(SetupStep.Removing, 0.95));- if (deleteSettings)- {- Log.Info($"Deleting the settings in {context.Paths.SettingsFolder}");- FileSwap.DeleteTree(context.Paths.SettingsFolder, System, Log);- }progress?.Report(new SetupProgress(SetupStep.Removing, 1));Log.Info("Uninstalled");return later;diff --git a/src/Filee.Setup/Platform/NativeMethods.cs b/src/Filee.Setup/Platform/NativeMethods.csindex a4a9c52b..f5794706 100644--- a/src/Filee.Setup/Platform/NativeMethods.cs+++ b/src/Filee.Setup/Platform/NativeMethods.cs@@ -34,6 +34,15 @@ internal static partial class NativeMethods[return: MarshalAs(UnmanagedType.Bool)]public static partial bool MoveFileEx(string existing, string? replacement, uint flags);+ private const uint SEM_FAILCRITICALERRORS = 0x0001;+ private const uint SEM_NOOPENFILEERRORBOX = 0x8000;++ [LibraryImport("kernel32.dll")]+ private static partial uint SetErrorMode(uint mode);++ /// <summary>No system error boxes (a missing drive, a program that can't start): Setup reports problems itself.</summary>+ public static void QuietErrors() => SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);+[LibraryImport("kernel32.dll", SetLastError = true)]private static partial nint OpenProcess(uint access, [MarshalAs(UnmanagedType.Bool)] bool inherit, uint processId);diff --git a/src/Filee.Setup/Platform/SetupSystem.cs b/src/Filee.Setup/Platform/SetupSystem.csindex 2b5e96f6..23fb22d6 100644--- a/src/Filee.Setup/Platform/SetupSystem.cs+++ b/src/Filee.Setup/Platform/SetupSystem.cs@@ -111,6 +111,13 @@ public class WindowsSetupSystem(SetupLog log) : ISetupSystempublic virtual int RunAndWait(string executable, string arguments, TimeSpan timeout){+ // Something that isn't a program (a damaged or half-written Filee.exe) makes Windows show "This app can't run+ // on your PC" and wait for an answer, even with Setup's error mode: never start one.+ if (!IsProgram(executable))+ {+ Log.Warn($"Not running {executable}: it is not a Windows program");+ return -1;+ }try{using var process = Process.Start(CreateStartInfo(executable, arguments));@@ -129,6 +136,20 @@ public class WindowsSetupSystem(SetupLog log) : ISetupSystem}}+ private static bool IsProgram(string path)+ {+ try+ {+ using var file = File.OpenRead(path);+ Span<byte> header = stackalloc byte[2];+ return file.Read(header) == 2 && header[0] == 'M' && header[1] == 'Z';+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ return false;+ }+ }+protected virtual ProcessStartInfo CreateStartInfo(string executable, string arguments) =>new(executable, arguments){diff --git a/src/Filee.Setup/Program.cs b/src/Filee.Setup/Program.csindex 0a6de9e7..e53edb9e 100644--- a/src/Filee.Setup/Program.cs+++ b/src/Filee.Setup/Program.cs@@ -36,6 +36,7 @@ internal static class Programreturn ExitInitFailed;// Never hold a folder Setup may delete (the install folder) as the current directory.Environment.CurrentDirectory = Environment.SystemDirectory;+ NativeMethods.QuietErrors();var options = SetupOptions.Parse(args);var exe = Environment.ProcessPath ?? Path.Combine(AppContext.BaseDirectory, "uninstall.exe");var sandbox = options.Sandbox is { } root ? Path.GetFullPath(root) : null;@@ -219,10 +220,12 @@ internal static class ProgramDirectory.CreateDirectory(temp);var copy = Path.Combine(temp, SetupNames.UninstallerExe);File.Copy(exe, copy);- var childArgs = args.Where(a => !HasName(a, "/DIR") && !HasName(a, "/LOG") && !HasName(a, "/UNINSTALL"))- .Concat(["/UNINSTALL", $"/DIR={folder}", $"/LOG={log.File}"]);+ var childArgs = args.Where(a => !HasName(a, "/DIR") && !HasName(a, "/LOG") && !HasName(a, "/UNINSTALL") && !HasName(a, "/FIRSTPHASE"))+ .Concat(["/UNINSTALL", $"/DIR={folder}", $"/LOG={log.File}", $"/FIRSTPHASE={Environment.ProcessId}"]);log.Info($"Continuing from {copy}");- var code = RunAndWait(copy, childArgs, elevated: needsAdmin, log);+ // Waits for the copy, or for its word that only this uninstall.exe is left (it then deletes it).+ var released = Path.Combine(temp, ReleasedFile);+ var code = RunAndWait(copy, childArgs, elevated: needsAdmin, log, until: () => File.Exists(released));if (code == ExitCancelled)TryDeleteFolder(temp);return code;@@ -233,7 +236,10 @@ internal static class Program// Phase 2: from a copy in %TEMP%.var fromTemp = Path.GetFileName(exeFolder).StartsWith("Filee-Uninstall-", StringComparison.OrdinalIgnoreCase);var trash = fromTemp ? Path.Combine(exeFolder, "trash") : Path.Combine(paths.Temp, $"Filee-Uninstall-{Guid.NewGuid():N}");- var runner = new SetupRunner(context, null, null, folder, record, trash);+ var runner = new SetupRunner(context, null, null, folder, record, trash)+ {+ ReleaseFirstPhase = options.FirstPhase is { } first && fromTemp ? () => ReleaseFirstPhase(exeFolder, first, log) : null,+ };int exitCode;if (options.Ui == SetupUi.VerySilent){@@ -266,6 +272,29 @@ internal static class Program}}+ /// <summary>Written by the uninstaller's copy when only uninstall.exe is left (see <see cref="Uninstaller.Run"/>).</summary>+ private const string ReleasedFile = "released";++ /// <summary>Tells the uninstaller in the install folder that it may end, and waits until it has.</summary>+ private static void ReleaseFirstPhase(string temp, int processId, SetupLog log)+ {+ try+ {+ using var first = Process.GetProcessById(processId);+ File.WriteAllText(Path.Combine(temp, ReleasedFile), "0");+ if (!first.WaitForExit(TimeSpan.FromSeconds(30)))+ log.Warn("The first uninstaller did not end");+ }+ catch (ArgumentException)+ {+ // Ended already.+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or Win32Exception or InvalidOperationException)+ {+ log.Warn($"Could not release the first uninstaller: {ex.Message}");+ }+ }+private static SetupContext CreateContext(string? sandbox, SetupPaths paths, SetupLog log){if (sandbox is null)@@ -320,7 +349,8 @@ internal static class Programreturn code;}- private static int RunAndWait(string exe, IEnumerable<string> args, bool elevated, SetupLog log)+ /// <param name="until">Stops waiting early when true (checked every 100 ms); the exit code is then 0.</param>+ private static int RunAndWait(string exe, IEnumerable<string> args, bool elevated, SetupLog log, Func<bool>? until = null){var info = new ProcessStartInfo(exe, SetupOptions.Join(args)){@@ -334,7 +364,14 @@ internal static class Programusing var child = Process.Start(info);if (child is null)return ExitInitFailed;- child.WaitForExit();+ while (!child.WaitForExit(100))+ {+ if (until?.Invoke() == true)+ {+ log.Info($"{Path.GetFileName(exe)} is done with this one");+ return ExitOk;+ }+ }log.Info($"{Path.GetFileName(exe)} ended with exit code {child.ExitCode}");return child.ExitCode;}@@ -453,11 +490,14 @@ internal sealed class SetupRunner(SetupContext context, SetupPayload? payload, Ppublic InstallResult Install(InstallChoices choices, IProgress<SetupProgress> progress) =>new Installer(context, payload ?? throw new InvalidOperationException("No payload.")).Run(choices, previous, progress);+ /// <summary>Lets the uninstaller in the install folder end before its file is deleted.</summary>+ public Action? ReleaseFirstPhase { get; init; }+public Exception? Uninstall(bool deleteSettings, IProgress<SetupProgress> progress){try{- new Uninstaller(context).Run(folder!, record!, deleteSettings, trash!, progress);+ new Uninstaller(context).Run(folder!, record!, deleteSettings, trash!, progress, ReleaseFirstPhase);return null;}catch (Exception ex) when (ex is not OutOfMemoryException)diff --git a/src/Filee.Setup/SetupOptions.cs b/src/Filee.Setup/SetupOptions.csindex 573dc6f4..9a43b51a 100644--- a/src/Filee.Setup/SetupOptions.cs+++ b/src/Filee.Setup/SetupOptions.cs@@ -28,6 +28,8 @@// /UNINSTALL uninstall (uninstall.exe, which has no payload, does this without the switch)// /LAUNCHFILE="file" internal: the unelevated Setup that asked for administrator rights starts Filee as the// signed-in user from what the elevated one writes into this file+// /FIRSTPHASE=<id> internal: the uninstaller's copy in %TEMP% lets the uninstaller in the install folder+// (process <id>) end before it deletes its filenamespace Filee.Setup;@@ -72,6 +74,7 @@ public sealed record SetupOptionspublic bool Uninstall { get; init; }public string? Sandbox { get; init; }public string? LaunchFile { get; init; }+ public int? FirstPhase { get; init; }/// <summary>Inno Setup switches that are accepted but change nothing.</summary>public IReadOnlyList<string> Ignored { get; init; } = [];@@ -154,6 +157,9 @@ public sealed record SetupOptionscase "SANDBOX" when !string.IsNullOrWhiteSpace(value):options = options with { Sandbox = value };break;+ case "FIRSTPHASE" when int.TryParse(value, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var id):+ options = options with { FirstPhase = id };+ break;case "LAUNCHFILE" when !string.IsNullOrWhiteSpace(value):options = options with { LaunchFile = value };break;diff --git a/tests/Filee.Setup.Tests/SetupOptionsTests.cs b/tests/Filee.Setup.Tests/SetupOptionsTests.csindex 01f90516..d4ab0076 100644--- a/tests/Filee.Setup.Tests/SetupOptionsTests.cs+++ b/tests/Filee.Setup.Tests/SetupOptionsTests.cs@@ -74,7 +74,9 @@ public class SetupOptionsTests[Fact]public void Filee_switches_and_unknown_arguments(){- var options = SetupOptions.Parse(["/NOLAUNCH", "/UNINSTALL", "/SANDBOX=D:\\scratch", "/LAUNCHFILE=C:\\t\\x.launch", "--weird", "/WHAT", "file.txt"]);+ var options = SetupOptions.Parse(["/NOLAUNCH", "/UNINSTALL", "/SANDBOX=D:\\scratch", "/LAUNCHFILE=C:\\t\\x.launch", "/FIRSTPHASE=4242", "--weird", "/WHAT", "file.txt"]);+ Assert.Equal(4242, options.FirstPhase);+ Assert.Null(SetupOptions.Parse(["/FIRSTPHASE=-1"]).FirstPhase);Assert.True(options.NoLaunch);Assert.True(options.Uninstall);Assert.Equal(@"D:\scratch", options.Sandbox);diff --git a/tests/Filee.Setup.Tests/UninstallerTests.cs b/tests/Filee.Setup.Tests/UninstallerTests.csindex 73d63e14..64f8adc8 100644--- a/tests/Filee.Setup.Tests/UninstallerTests.cs+++ b/tests/Filee.Setup.Tests/UninstallerTests.cs@@ -90,6 +90,24 @@ public class UninstallerTests}}+ [Fact]+ public void The_waiting_uninstaller_is_released_last_before_its_file_goes()+ {+ var (bench, record) = Installed();+ using var _ = bench;+ var uninstaller = Path.Combine(bench.InstallFolder, "uninstall.exe");+ var seen = new List<string>();+ new Uninstaller(bench.Context).Run(bench.InstallFolder, record, deleteSettings: false, bench.Temp.Sub("trash"),+ releaseUninstaller: () =>+ {+ // Everything else is gone by now, the uninstall entry too; only the uninstaller is left.+ seen.AddRange(Directory.EnumerateFiles(bench.InstallFolder, "*", SearchOption.AllDirectories));+ Assert.False(bench.Registry.KeyExists(Hive.LocalMachine, SetupNames.UninstallKey));+ });+ Assert.Equal([uninstaller], seen);+ Assert.False(Directory.Exists(bench.InstallFolder));+ }+[Fact]public void Programs_left_running_are_ended_but_not_the_uninstaller_that_waits(){