2017-05-09 9 views
-1

特定のフォルダ内のすべてのファイルをウィンドウを開かずに削除したいが、削除できないファイルのためにエラーが発生した場合は、それを削除しません。フォルダ内のファイルを削除する(Visual Studio 2017 VB.NET)

例:ノーリターンメッセージやエラーで

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 
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 
関連する問題