“MoveFile” function in C# (Delete file after reboot)

You’ll need the P/Invoke declarations for MoveFileEx:

[Flags]
internal enum MoveFileFlags
{
    None = 0,
    ReplaceExisting = 1,
    CopyAllowed = 2,
    DelayUntilReboot = 4,
    WriteThrough = 8,
    CreateHardlink = 16,
    FailIfNotTrackable = 32,
}

internal static class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
    public static extern bool MoveFileEx(
        string lpExistingFileName,
        string lpNewFileName, 
        MoveFileFlags dwFlags);
}

And some example code:

if (!NativeMethods.MoveFileEx("a.txt", null, MoveFileFlags.DelayUntilReboot))
{
    Console.Error.WriteLine("Unable to schedule 'a.txt' for deletion");
}

Leave a Comment