How to fast delete many files

前端 未结 3 1452
梦如初夏
梦如初夏 2021-01-21 19:09

I have a folder in Windows Server with subfolders and ≈50000 files. When I click the right mouse button and choose delete (or shift+delete) – all files are deleted in 10-20 seco

3条回答
  •  渐次进展
    2021-01-21 20:02

    A much faster way to delete files is to use the Windows functions instead of the .NET ones.

    You will need to first import the function:

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool DeleteFile(string lpFileName);
    

    And then you can do this:

    string[] files = Directory.EnumerateFiles(path, "*". SearchOption.AllDirectories);
    
    foreach (string file in files)
    {
        DeleteFile(file);
    }
    

    Once the files are deleted, which is the slowest part by using the managed APIs, you can call Directory.DeleteFolder(path, true) to delete the empty folders.

提交回复
热议问题