Mark File for deletion on reboot

Requirement: Delete files from a given folder using C#.

Challenge: The file may be in use i.e. locked.

Approach: Use System Call to mark file for deletion on restart

Solution: Use PInvoke for MoveFileEx.

///
/// Consts defined in WINBASE.H
///
internal enum MoveFileFlags
{
    MOVEFILE_REPLACE_EXISTING = 1,
    MOVEFILE_COPY_ALLOWED = 2,
    MOVEFILE_DELAY_UNTIL_REBOOT = 4,
    MOVEFILE_WRITE_THROUGH  = 8
}


/// 
/// Marks the file for deletion during next system reboot
/// 
/// The current name of the file or directory on the local computer.
/// The new name of the file or directory on the local computer.
/// MoveFileFlags
/// bool
/// http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx
[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll",EntryPoint="MoveFileEx")]
internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName,
MoveFileFlags dwFlags);

//Usage for marking the file to delete on reboot
MoveFileEx(fileToDelete, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);

The file is marked for deletion in registry in following location

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerPendingFileRenameOperations