我想删除特定文件夹中的所有可能文件,而不打开任何窗口,如果由于无法删除的文件而发生错误,则只是不删除它。
示例:
DeleteFilesInsideFolder("C:\Windows\Temp")
没有返回消息或错误。
答案 0 :(得分:0)
这是一个删除指定文件夹中所有文件的函数:
Imports System.IO
Sub DeleteFilesInsideFolder(ByVal target_folder_path As String)
' loop through each file in the target directory
For Each file_path As String In Directory.GetFiles(target_folder_path)
' delete the file if possible...otherwise skip it
Try
File.Delete(file_path)
Catch ex As Exception
End Try
Next
End Sub
但是,如果您还想删除子目录,则需要使用此修改版本:
Imports System.IO
Sub DeleteFilesInsideFolder(ByVal target_folder_path As String, ByVal also_delete_sub_folders As Boolean)
' loop through each file in the target directory
For Each file_path As String In Directory.GetFiles(target_folder_path)
' delete the file if possible...otherwise skip it
Try
File.Delete(file_path)
Catch ex As Exception
End Try
Next
' if sub-folders should be deleted
If also_delete_sub_folders Then
' loop through each file in the target directory
For Each sub_folder_path As String In Directory.GetDirectories(target_folder_path)
' delete the sub-folder if possible...otherwise skip it
Try
Directory.Delete(sub_folder_path, also_delete_sub_folders)
Catch ex As Exception
End Try
Next
End If
End Sub
答案 1 :(得分:0)
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim path As String = "E:\NewFolder\"
DeleteDirectory(path)
End Sub
Private Sub DeleteDirectory(path As String)
If Directory.Exists(path) Then
'Delete all files from the Directory
For Each filepath As String In Directory.GetFiles(path)
File.Delete(filepath)
Next
'Delete all child Directories
For Each dir As String In Directory.GetDirectories(path)
DeleteDirectory(dir)
Next
'Delete a Directory
Directory.Delete(path)
End If
End Sub