如何在不删除文件夹本身或其任何子文件夹的情况下删除文件夹中的所有文件,包括子文件夹中的文件 [英] 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

查看:36
本文介绍了如何在不删除文件夹本身或其任何子文件夹的情况下删除文件夹中的所有文件,包括子文件夹中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想要的是:

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

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.

推荐答案

试试这个递归子

 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")

这篇关于如何在不删除文件夹本身或其任何子文件夹的情况下删除文件夹中的所有文件,包括子文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆