vb.net 如何在不删除文件夹本身或其任何子文件夹的情况下删除文件夹中的所有文件,包括子文件夹中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25221181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:01:10  来源:igfitidea点击:

How to delete all the files in a folder including the files in the sub folders without deleting the the folder itself or any of its sub folders

vb.net

提问by Dipojjal

I want to delete all the files contained in a folder. The code I am using deletes all the files in the root folder but it does not delete the files inside the sub folders. Here is the code:

我想删除文件夹中包含的所有文件。我使用的代码会删除根文件夹中的所有文件,但不会删除子文件夹中的文件。这是代码:

If Not Directory.Exists("C:\New Folder") Then
   Return
End If

Dim files() As String
files = Directory.GetFileSystemEntries("C:\New Folder")

For Each element As String In files
   If (Not Directory.Exists(element)) Then
      File.Delete(Path.Combine("C:\New Folder", Path.GetFileName(element)))
   End If
Next

What I want here is:

我想要的是:

I want to delete all the files inside the folder “New Folder”. At the same time, I want to keep the sub folders and delete all the files it contains. So, after the operation, “New Folder” may have any number of sub folders but it should not have even a single file.

我想删除文件夹“新建文件夹”中的所有文件。同时,我想保留子文件夹并删除它包含的所有文件。所以,在操作之后,“新建文件夹”可以有任意数量的子文件夹,但它不应该有一个文件。

回答by Nizam

Try this recursive sub

试试这个递归子

 Sub DeleteFilesFromFolder(Folder As String)
    If Directory.Exists(Folder) Then
        For Each _file As String In Directory.GetFiles(Folder)
            File.Delete(_file)
        Next
        For Each _folder As String In Directory.GetDirectories(Folder)

            DeleteFilesFromFolder(_folder)
        Next

    End If

End Sub

'Somewhere you call

DeleteFilesFromFolder("C:\New Folder")