删除除 3 个文件之外的所有文件 VB.NET

Delete all files except 3 files VB.NET

我有这个代码

 Private Sub DeleteOldFiles(
        ByVal AsDirectoryName As String,
        ByVal AbDeleteSubDirectories As Boolean,
        ByVal AbDeleteFolders As Boolean)

        If AbDeleteSubDirectories Then
            Dim m_sSubdirectoryName As String

            For Each m_sSubdirectoryName In
            System.IO.Directory.GetDirectories(AsDirectoryName)
                DeleteOldFiles _
                    (m_sSubdirectoryName,
                    AbDeleteSubDirectories,
                    AbDeleteFolders)

                If AbDeleteFolders Then
                    System.IO.Directory.Delete(m_sSubdirectoryName)
                End If
            Next
        End If

        Dim m_sFileName As String

        For Each m_sFileName In
        System.IO.Directory.GetFiles(AsDirectoryName)
            If m_sFileName <> "p2ptv_preview01.zip" Then
                System.IO.File.Delete(m_sFileName)
            End If
        Next

和 DeleteOldFiles("./", True, True) 在按钮控件上。 但是,此代码仅适用于一个文件。 我想排除更多文件。 我该怎么做?

只需传入一个您不想删除的豁免文件列表,然后查看当前文件名是否在该列表中。

Private Sub DeleteOldFiles(
    ByVal AsDirectoryName As String,
    ByVal AbDeleteSubDirectories As Boolean,
    ByVal AbDeleteFolders As Boolean,
    ByVal exemptFileNames As IEnumerable(Of String))

    If AbDeleteSubDirectories Then
        Dim m_sSubdirectoryName As String

        For Each m_sSubdirectoryName In
        System.IO.Directory.GetDirectories(AsDirectoryName)
            DeleteOldFiles _
                (m_sSubdirectoryName,
                AbDeleteSubDirectories,
                AbDeleteFolders,
                exemptFileNames)

            If AbDeleteFolders Then
                System.IO.Directory.Delete(m_sSubdirectoryName)
            End If
        Next
    End If

    Dim m_sFileName As String

    For Each m_sFileName In
    System.IO.Directory.GetFiles(AsDirectoryName)
        If exemptFileNames.Contains(m_sFileName) Then
            Console.WriteLine("Skipped " & m_sFileName)
        Else
            System.IO.File.Delete(m_sFileName)
        End If
    Next
End Sub

用法:

Sub Main()
    Dim exemptFilenames As New List(Of String)()
    exemptFilenames.Add("p2ptv_preview01.zip")
    exemptFilenames.Add("name2.txt")
    exemptFilenames.Add("name3.tar")
    DeleteOldFiles("./", True, True, exemptFilenames)
End Sub