Marking files for deletion using MoveFileEx

2.9k views Asked by At

I'm having a bit of trouble getting MoveFileEx to work properly in Windows 7 x64.

I'm running my application as administrator, marking files for deletion on next reboot but after rebooting find that none of the files are being deleted.

I'm using the following to accomplish said feat:

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);

    private static IEnumerable<string> GetFiles(string path)
    {
        var queue = new Queue<string>();
        queue.Enqueue(path);
        while (queue.Count > 0)
        {
            path = queue.Dequeue();
            try
            {
                foreach (var subDir in Directory.GetDirectories(path))
                {
                    queue.Enqueue(subDir);
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
            string[] files = null;
            try
            {
                files = Directory.GetFiles(path);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
            if (files != null)
            {
                foreach (var t in files)
                {
                    yield return t;
                }
            }
        }
    }
 private void button1_Click(object sender, EventArgs e)
{
  foreach (var files in GetFiles(sysRoot + @"\system32\spool\drivers\x64\"))
  {
    Log(files);
    MoveFileEx(files, null, MoveFileFlags.MovefileDelayUntilReboot);
  }
}

I can verify the marking process is being done on multiple files, just can't figure out why it's not then performing the delete functionality after the machine has been rebooted.

Any assistance in this area will be greatly appreciated.

Thank you.

2

There are 2 answers

4
StilesCrisis On

If these are driver files that are loaded as soon as the machine boots, they might not be deletable because they are open/in-use.

1
Hans Passant On

You are making a pretty classic winapi mistake. You set the SetLastError property to true but then don't actually check if the function failed. Modify your code like this:

if (!MoveFileEx(files, null, MoveFileFlags.MovefileDelayUntilReboot)) {
    throw new System.ComponentModel.Win32Exception();
}

Now you'll know why it failed.