如何标记要删除的文件夹C#

问题描述 投票:6回答:4

如何在系统重新启动时使用C#标记一个文件夹以进行删除。

谢谢,

c# windows
4个回答
19
投票

最初是从:

http://abhi.dcmembers.com/blog/2009/03/24/mark-file-for-deletion-on-reboot/

文档:

https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-movefileexa#parameters

///
/// Consts defined in WINBASE.H
///
[Flags]
internal enum MoveFileFlags
{
    MOVEFILE_REPLACE_EXISTING = 1,
    MOVEFILE_COPY_ALLOWED = 2,
    MOVEFILE_DELAY_UNTIL_REBOOT = 4, //This value can be used only if the process is in the context of a user who belongs to the administrators group or the LocalSystem account
    MOVEFILE_WRITE_THROUGH  = 8
}


/// <summary>
/// Marks the file for deletion during next system reboot
/// </summary>
/// <param name="lpExistingFileName">The current name of the file or directory on the local computer.</param>
/// <param name="lpNewFileName">The new name of the file or directory on the local computer.</param>
/// <param name="dwFlags">MoveFileFlags</param>
/// <returns>bool</returns>
/// <remarks>http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx</remarks>
[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);

3
投票

使用PInvoke并调用MoveFileEx,将null作为目标传递....

This link有一些示例代码:

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, int dwFlags);

public const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;

MoveFileEx(filename, null, MOVEFILE_DELAY_UNTIL_REBOOT);


0
投票

问题是使用MOVEFILE_DELAY_UNTIL_REBOOT与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 } /// <summary> /// Marks the file for deletion during next system reboot /// </summary> /// <param name="lpExistingFileName">The current name of the file or directory on the local computer.</param> /// <param name="lpNewFileName">The new name of the file or directory on the local computer.</param> /// <param name="dwFlags">MoveFileFlags</param> /// <returns>bool</returns> /// <remarks>http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx</remarks> [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);

我的解决方案如下:使用MOVEFILE_DELAY_UNTIL_REBOOT将MoveFileEx“删除”目录中的每个文件,然后以相同的方式“删除”目录。

Reference to documentation.
© www.soinside.com 2019 - 2024. All rights reserved.