关于使用vb.net的子文件夹下的文件夹

时间:2012-03-06 11:52:55

标签: vb.net file directory

我想删除所有根目录下的文件夹e:\ trichy.root文件夹还包含子文件夹,如e:\ trichy \ chn \ 20008 \ 20204 * .mp3文件。请帮助我 。总是收到错误。

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

请帮我删除子文件夹下的这个根文件夹下的文件吗?

3 个答案:

答案 0 :(得分:1)

根本不需要FileInfo对象。我没有测试过,但它可能只是一种不必要的浪费或资源,而且性能昂贵。

试试这个:

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

用法:

DeleteOldFiles(txtRootFolder.Text, Now.AddMonths(-3), "*.mp3")

答案 1 :(得分:0)

删除指定的目录,如果指示,则删除目录中的所有子目录和文件。

  Directory.Delete(Path1, true)

MSDN

答案 2 :(得分:0)

Directory.GetDirectories返回所有子目录。然后你要从中创建FileInfo个对象。

我认为你想要删除该文件夹中的文件,而不是需要使用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")

如果要以递归方式删除所有子文件夹中的所有文件:

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 

你会称之为:

ProcessDirectory(rootfolder1)