[英]How to synchronously and consistently delete a folder on NTFS with C#
這個:
Directory.Delete(dir, true);
不是同步的。
在緊接着的行中,您仍然可以操作/讀取目錄。
例如,這個:
Directory.Delete(destinationDir, true);
Directory.CreateDirectory(destinationDir);
Thread.Sleep(1000);
導致文件夾不存在。 刪除運行異步, CreateDirectory
不創建,因為它已經存在,然后刪除實際觸發並刪除目錄。
是否有一個IO API可以提供一致性?
涉及Thread.Sleep
答案將調用Zalgo。 我想要一個真正的解決方案。
正如其他人所提到的那樣,.net Framework似乎並沒有同步運行它。 在PowerShell中測試它表明.Net調用不會等待,所以這樣的事情會產生類似的結果:
Remove-Item -Recurse -Force "C:\tempfolder"
New-Item -ItemType Directory "C:\tempfolder"
使用文件觀察器(前面也提到過)將確保在創建完成之前完成目錄刪除:
var path = @"C:\tempfolder";
var watcher = new FileSystemWatcher(path);
watcher.Deleted += (sender, args) => Directory.CreateDirectory(args.FullPath);
Directory.Delete(path, true);
沒有真正意外,但至少它是一個有效的解決方案,不涉及從托管代碼調用C ++ API。
這是一個有相同問題的人的鏈接 ,首先重命名/移動目錄的解決方案可能適合您。
否則你可以使用FileWatcher來對目錄刪除作出反應,但這感覺就像是矯枉過正。
在C ++中進行一些測試后,似乎用於刪除文件/目錄的本機Windows功能會阻塞。 當刪除函數未被阻止時,似乎問題出現在.NET端,因為Directory.CreateDirectory()
似乎在Directory.Delete()
完成之前被調用。
這是我在Win32控制台應用程序中嘗試的:
printf("Press enter to begin...");
while(getchar() != '\n');
LPCSTR DeletePath = "C:\\test\\DeleteMe"; //The directory to delete.
_SHFILEOPSTRUCTA* fileopt = new _SHFILEOPSTRUCTA();
fileopt->hwnd = NULL; //No window handle.
fileopt->wFunc = FO_DELETE; //Delete mode.
fileopt->pFrom = DeletePath; //The directory to delete.
fileopt->pTo = NULL; //No target directory (this is only used when moving, copying, etc.).
fileopt->fFlags = FOF_NO_UI; //Display no UI dialogs.
int Success = SHFileOperationA(fileopt); //Remove the entire directory and all it's contents.
bool Success2 = CreateDirectoryA(DeletePath, NULL); //Create a new directory.
LPCSTR ReturnedValue = "False"; //I'm no C++ guru, so please don't hate. :)
LPCSTR ReturnedValue2 = "False";
if(Success == 0) { ReturnedValue = "True"; } //The SHFileOperation() returns 0 if it succeeds.
if(Success2 == true) { ReturnedValue2 = "True"; }
//Print the result of SHFileOperation().
printf("Returned value: ");
printf(ReturnedValue);
printf("\n");
//Print the result of CreateDirectory().
printf("Returned value 2: ");
printf(ReturnedValue2);
printf("\n");
//Continue.
printf("Press enter to exit...");
while(getchar() != '\n');
在第一次按下ENTER之后,在顯示結果之前會有一個小的延遲,然后在查看文件夾后,它會為空,帶有新的創建和最后修改日期 - 這意味着它已被刪除並以正確的順序重新創建。
所以為了實現你想要的,我想你可以嘗試創建自己的方法來調用SHFileOperation()
,因為問題似乎是Directory.Delete()
方法在.NET代碼中執行迭代(參見參考資料來源 )。
在C#中測試后,這似乎有效! 唯一的問題是,第一次(自應用程序啟動以來)調用P / Invoked SHFileOperation()
函數,它將返回值2,這相當於ERROR_FILE_NOT_FOUND
。 但如果再次執行它將返回0(成功)。
NativeMethods.cs:
需要進口:
using System;
using System.Runtime.InteropServices;
其余代碼:
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
public static extern int SHFileOperation([In] ref SHFILEOPSTRUCT lpFileOp);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SHFILEOPSTRUCT
{
public IntPtr hwnd;
public FileFuncFlags wFunc;
[MarshalAs(UnmanagedType.LPWStr)]
public string pFrom;
[MarshalAs(UnmanagedType.LPWStr)]
public string pTo;
public FILEOP_FLAGS fFlags;
[MarshalAs(UnmanagedType.Bool)]
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
[MarshalAs(UnmanagedType.LPWStr)]
public string lpszProgressTitle;
}
public enum FileFuncFlags : uint
{
FO_MOVE = 0x1,
FO_COPY = 0x2,
FO_DELETE = 0x3,
FO_RENAME = 0x4
}
[Flags]
public enum FILEOP_FLAGS : ushort
{
FOF_MULTIDESTFILES = 0x1,
FOF_CONFIRMMOUSE = 0x2,
/// <summary>
/// Don't create progress/report
/// </summary>
FOF_SILENT = 0x4,
FOF_RENAMEONCOLLISION = 0x8,
/// <summary>
/// Don't prompt the user.
/// </summary>
FOF_NOCONFIRMATION = 0x10,
/// <summary>
/// Fill in SHFILEOPSTRUCT.hNameMappings.
/// Must be freed using SHFreeNameMappings
/// </summary>
FOF_WANTMAPPINGHANDLE = 0x20,
FOF_ALLOWUNDO = 0x40,
/// <summary>
/// On *.*, do only files
/// </summary>
FOF_FILESONLY = 0x80,
/// <summary>
/// Don't show names of files
/// </summary>
FOF_SIMPLEPROGRESS = 0x100,
/// <summary>
/// Don't confirm making any needed dirs
/// </summary>
FOF_NOCONFIRMMKDIR = 0x200,
/// <summary>
/// Don't put up error UI
/// </summary>
FOF_NOERRORUI = 0x400,
/// <summary>
/// Dont copy NT file Security Attributes
/// </summary>
FOF_NOCOPYSECURITYATTRIBS = 0x800,
/// <summary>
/// Don't recurse into directories.
/// </summary>
FOF_NORECURSION = 0x1000,
/// <summary>
/// Don't operate on connected elements.
/// </summary>
FOF_NO_CONNECTED_ELEMENTS = 0x2000,
/// <summary>
/// During delete operation,
/// warn if nuking instead of recycling (partially overrides FOF_NOCONFIRMATION)
/// </summary>
FOF_WANTNUKEWARNING = 0x4000,
/// <summary>
/// Treat reparse points as objects, not containers
/// </summary>
FOF_NORECURSEREPARSE = 0x8000
}
其他地方:
string DeletePath = "C:\\test\\DeleteMe";
NativeMethods.SHFILEOPSTRUCT fileopt = new NativeMethods.SHFILEOPSTRUCT();
fileopt.hwnd = IntPtr.Zero;
fileopt.wFunc = NativeMethods.FileFuncFlags.FO_DELETE;
fileopt.pFrom = DeletePath;
fileopt.pTo = null;
fileopt.fFlags = NativeMethods.FILEOP_FLAGS.FOF_SILENT | NativeMethods.FILEOP_FLAGS.FOF_NOCONFIRMATION |
NativeMethods.FILEOP_FLAGS.FOF_NOERRORUI | NativeMethods.FILEOP_FLAGS.FOF_NOCONFIRMMKDIR; //Equivalent of FOF_NO_UI.
int Success = NativeMethods.SHFileOperation(ref fileopt);
Directory.CreateDirectory(DeletePath);
MessageBox.Show("Operation returned value: " + Success.ToString(), "Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.