Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"MoveFile" function in C# (Delete file after reboot)

Tags:

c#

.net

windows

I am in need of an example, that can let me pass a parameter

e.g. executing delete.exe /killme.txt

So it will use the "MoveFile" to delete killme.txt after reboot.

Although please not the MS precompiled version, as it has an annoying disclaimer, every time its run on a different computer.

like image 739
Jay Avatar asked May 20 '11 21:05

Jay


Video Answer


1 Answers

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");
}
like image 145
user7116 Avatar answered Oct 26 '22 17:10

user7116