简体   繁体   中英

Marking files for deletion using MoveFileEx

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.

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.

如果这些是机器启动后立即加载的驱动程序文件,则由于它们已打开/正在使用中,因此可能无法删除。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM