Mario Bălănică Mario Bălănică - 4 months ago 19
Vb.net Question

Delete all files except 3 files VB.NET

I have this code

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


and DeleteOldFiles("./", True, True) on a button control.
but, this code works only with one file.
i want to except more files.
how can I do this?

Answer

Just pass in a list of exempt files you don't want to delete and see if the current filename is in that list.

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

Usage:

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