Reputation: 37
i want to delete all the under root folder e:\trichy.root folder contain also sub folder like e:\trichy\chn\20008\20204*.mp3 files. pls help me . always getting an error.
Dim rootfolder1 As FileInfo
rootfolder1 = txtRootFolder.Text
Try
If Directory.Exists(rootfolder1) Then
Dim files() As String = Directory.GetDirectories(rootfolder1)
For Each file As String In files
Dim fi As FileInfo = New FileInfo(file)
If (fi.LastAccessTime < DateTime.Now.AddMonths(-3)) Then
fi.Delete()
display_status("files are deleted successfully")
End If
Next
End If
Catch ex As Exception
display_status("Error in file deletion" & ex.Message)
End Try
pls help me to delete files under this root folder under subfolder?
Upvotes: 0
Views: 955
Reputation: 6969
You don't need the FileInfo objects at all. I have not tested, but it may just be an unnecessary waste or resources, and expensive performancewise.
Try this:
Private Sub DeleteOldFiles(ByVal rootFolder As String, ByVal uptoDate As Date, Optional ByVal fileTypes As String = "*.*")
Try
If Directory.Exists(rootFolder) Then
Dim files() As String = Directory.GetFiles(rootFolder, fileTypes, SearchOption.AllDirectories)
For Each f As String In files
If File.GetLastAccessTime(f) <= uptoDate Then
File.Delete(f)
End If
Next
End If
display_status("files are deleted successfully")
Catch ex As Exception
display_status("Error in file deletion" & ex.Message)
End Try
End Sub
Usage:
DeleteOldFiles(txtRootFolder.Text, Now.AddMonths(-3), "*.mp3")
Upvotes: 1
Reputation: 460018
Directory.GetDirectories
returns all sub-directories. Then you're creating FileInfo
objects from it.
I assume that you instead want to delete the files in that folder, than you need to use Directory.GetFiles
:
Dim files() As String = Directory.GetFiles(rootfolder1)
For Each file As String In files
Dim fi As FileInfo = New FileInfo(file)
If (fi.LastAccessTime < DateTime.Now.AddMonths(-3)) Then
fi.Delete()
End If
Next
display_status("files are deleted successfully")
If you want to delete all files in all sub-folders recursively:
Public Shared Sub ProcessDirectory(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
Dim fileName As String
For Each fileName In fileEntries
Dim fi As FileInfo = New FileInfo(fileName)
If (fi.LastAccessTime < DateTime.Now.AddMonths(-3)) Then
fi.Delete()
End If
Next fileName
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
' Recurse into subdirectories of this directory.
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
ProcessDirectory(subdirectory)
Next subdirectory
End Sub
You would call it:
ProcessDirectory(rootfolder1)
Upvotes: 0