Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除文件夹中的项目,而不是使用vb.net删除整个文件夹本身_Vb.net_File - Fatal编程技术网

删除文件夹中的项目,而不是使用vb.net删除整个文件夹本身

删除文件夹中的项目,而不是使用vb.net删除整个文件夹本身,vb.net,file,Vb.net,File,我想删除文件夹中包含的所有文件。下面的代码确实删除了文件,但也删除了文件夹本身。我知道您将需要执行for循环以从文件夹中删除每个项目,但找不到有关如何为其启动代码的信息。有人能给我指一下正确的方向吗 Dim folderFiles() As String folderFiles= Directory.GetFileSystemEntries("C:\New Folder") For Each element As String In files If (Not Dir

我想删除文件夹中包含的所有文件。下面的代码确实删除了文件,但也删除了文件夹本身。我知道您将需要执行for循环以从文件夹中删除每个项目,但找不到有关如何为其启动代码的信息。有人能给我指一下正确的方向吗

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

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

这是更简单的方法:

For Each the_file As String In Directory.GetFileSystemEntries("C:\New folder")
   File.Delete(the_file)
Next

不要费心抓取文件列表,然后浏览它,直接在上面使用循环。

我有一个功能。使用它,您还可以删除模式的所有文件,即使是所有子目录:

Public Sub DeleteFiles(Path As String,
                       Optional Pattern As String = "*.*",
                       Optional All As Boolean = False)
    Dim SO As IO.SearchOption = If(All, IO.SearchOption.AllDirectories, IO.SearchOption.TopDirectoryOnly)

    For Each Filename As String In Directory.GetFiles(Path, Pattern, SO)
        File.Delete(Filename)
    Next
End Sub
因此,您可以将其用于您的任务,如:

DeleteFiles("C:\New Folder")
我会使用这个代码

    For Each file As String In IO.Directory.GetFiles("the path")

            IO.File.Delete(file)

    Next

这将删除文件夹中的所有内容,但不会删除文件夹本身。

这是一种快速而简单的操作,尤其是在以下情况下:1)文件夹没有任何特殊之处,例如权限;2)文件夹可能包含子文件夹、子子文件夹等

只需删除原始文件夹并重新创建:

Dim path As String = {your path}
IO.Directory.Delete(path, recursive:=True)
IO.Directory.CreateDirectory(path)
对于包含子文件夹且希望保留(空)子文件夹的文件夹,另一个选项是使用递归:

Sub EmptyFolder(path As String) As Boolean
    Try
        For Each dir As String In IO.Directory.GetDirectories(path)
            EmptyFolder(dir)
        Next dir
        For Each file As String In IO.Directory.GetFiles(path)
            IO.File.Delete(file)
        Next file
    Catch
        Throw
    End Try
End Function