Results 1 to 10 of 10

Thread: VB.NET - Search directories, subdirectories for files, excluding files by name or ext

  1. #1

    Thread Starter
    Fanatic Member Peter Porter's Avatar
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    538

    Thumbs up VB.NET - Search directories, subdirectories for files, excluding files by name or ext

    Written in VB.NET 2010, the below code searches a select directory and it's subdirectories for all files... gets file extensions and excludes files by select extensions from whatever function you want to perform, like deletion, copying, whatever, all while it's recording how many times it loops, not counting excluded files from skipped loops. To test the code, you'll gonna need one button, a label called "Processed:" next to a textbox.

    Note: The .suo file extension, which is a file extension I excluded in the code below, is a hidden file VB.NET adds to your projects with the same project name. The program only works by ignoring hidden .suo and .ini files.

    Hope someone finds this helpful!

    Code:
    Option Strict On
    
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim i as integer = 0
    
             'Target Directory
            Dim directory = "C:\Users\Peter\Desktop\TestFolder\"
    
              'Searches directory and it's subdirectories for all files, which "*" stands for
              'Say for example you only want to search for jpeg files... then change "*" to "*.jpg"  
            For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
    
                 'The next line of code gets only file extensions from searched directories and subdirectories
                Dim fName As String = IO.Path.GetExtension(filename)
    
                If fName = ".suo" Then
                    
                    'Skips to next iteration of Loop, ignoring files with .suo extension 
                    Continue For
    
                Else
                    If fName = ".ini" Then
    
                        'Skips to next iteration of Loop, ignoring files with .ini extension
                        Continue For
    
                    Else
    
                        'Your code here above count function
                        'The below counter only displays the final count after all files have been processed
    
                        i = i + 1
                        TextBox1.Text = Convert.ToString(i)
    
                    End If
                End If
            Next
        End Sub
    End Class
    If you would like to filter files by name, copy the fName array line, change fName to fName2 and change GetExtension to GetFileName or GetFileNameWithoutExtension from your new array. You then would have to create If Then statements for this new array. Like I stated above, this program only works by ignoring .suo and .ini files, so I wouldn't change anything, but add to above.
    Last edited by Peter Porter; Jul 12th, 2013 at 09:08 AM.

  2. #2

    Thread Starter
    Fanatic Member Peter Porter's Avatar
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    538

    VB.NET - Delete files in directory and subdirectories, excluding select extensions

    Code:
    Option Strict On
    
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim i as integer = 0
    
             'Target Directory
            Dim directory = "C:\Users\Peter\Desktop\TestFolder\"
    
              'Searches directory and it's subdirectories for all files, which "*" stands for
              'Say for example you only want to search for jpeg files... then change "*" to "*.jpg"  
            For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
    
                 'The next line of code gets only file extensions from searched directories and subdirectories
                Dim fName As String = IO.Path.GetExtension(filename)
    
                If fName = ".suo" Then
                    
                    'Skips to next iteration of Loop, ignoring files with .suo extension 
                    Continue For
    
                Else
                    If fName = ".ini" Then
    
                        'Skips to next iteration of Loop, ignoring files with .ini extension
                        Continue For
    
                    Else
    
                        'Kill function deletes all files in target directory and it's subdirectories 
                        'except for files with the .suo and .ini extension
                        System.IO.File.Delete(directory & fName)
    
                        'The below counter only displays the final count after all files have been processed
                        i = i + 1
                        TextBox1.Text = Convert.ToString(i)
    
                    End If
                End If
            Next
        End Sub
    End Class

    You could also use the code without the If Then Statements. The .sou and .ini files gave me trouble because my Else event was complex. The following code might also delete those extensions:

    Code:
    Option Strict On
    
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim i as integer = 0
    
             'Target Directory
            Dim directory = "C:\Users\Peter\Desktop\TestFolder\"
    
              'Searches directory and it's subdirectories for all files, which "*" stands for
              'Say for example you only want to search for jpeg files... then change "*" to "*.jpg"  
            For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
    
                        'Kill function deletes all files in target directory and it's subdirectories 
                        System.IO.File.Delete(directory & fName)
    
                        'The below counter only displays the final count after all files have been processed
                        i = i + 1
                        TextBox1.Text = Convert.ToString(i)
               
            Next
        End Sub
    End Class
    Last edited by Peter Porter; Jul 20th, 2015 at 09:31 AM. Reason: Added code

  3. #3

    Thread Starter
    Fanatic Member Peter Porter's Avatar
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    538

    VB.NET - Delete files in directories and subdirectories, excluding select file names

    I've changed the fName array GetExtension to GetFilename. The If Then statements now show the file names to ignore, backup.txt and log.txt:

    Code:
    Option Strict On
    
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim i as integer = 0
    
             'Target Directory
            Dim directory = "C:\Users\Peter\Desktop\TestFolder\"
    
              'Searches directory and it's subdirectories for all files, which "*" stands for
              'Say for example you only want to search for jpeg files... then change "*" to "*.jpg"
            For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
    
                 'The next line of code gets file names with extensions from searched directories and subdirectories
                Dim fName As String = IO.Path.GetFileName(filename)
    
                If fName = "backup.txt" Then
                    
                    'Skips to next iteration of Loop, ignoring backup files with the txt extension 
                    Continue For
    
                Else
                    If fName = "log.txt" Then
    
                        'Skips to next iteration of Loop, ignoring log files with the txt extension
                        Continue For
    
                    Else
    
                        'Deletes all files in target directory and it's subdirectories 
                        'except for the backup.txt and log.txt files
                        System.IO.File.Delete(directory & fName)
    
                        'The below counter only displays the final count after all files have been processed
                        i = i + 1
                        TextBox1.Text = Convert.ToString(i)
    
                    End If
                End If
            Next
        End Sub
    End Class
    Last edited by Peter Porter; Jul 23rd, 2015 at 10:59 AM.

  4. #4
    Junior Member
    Join Date
    Jun 2013
    Posts
    19

    Re: VB.NET - Search directories, subdirectories for files, excluding files by name or

    Peter, I just tried your code and it gives me an "access denied" error for certain directories, which breaks the for-next loop. How can I ignore that particular directory and go on?

    TIA...

  5. #5
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,398

    Re: VB.NET - Search directories, subdirectories for files, excluding files by name or

    There are a few issues with your submission. There is no logic to check for a file type and then do nothing with it.

    vb Code:
    1. Option Strict On
    2.  
    3. Public Class Form1
    4.  
    5.     Private Sub Foo(ByVal directory As String)
    6.  
    7.         For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
    8.  
    9.             Dim fName As String = IO.Path.GetExtension(filename)
    10.  
    11.             If fName = ".suo" Then
    12.  
    13.                 Continue For
    14.  
    15.             Else
    16.                 If fName = ".ini" Then
    17.  
    18.                     Continue For
    19.  
    20.                 Else
    21.  
    22.  
    23.                 End If
    24.             End If
    25.         Next
    26.     End Sub
    27. End Class

    fName is not exactly descriptive either, especially as it's not a name you are retrieving.

    vb Code:
    1. Option Strict On
    2.  
    3. Public Class Form1
    4.  
    5.     Private Sub Foo(ByVal directory As String)
    6.         For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
    7.  
    8.             Dim fileExtension As String = IO.Path.GetExtension(filename)
    9.  
    10.             If fileExtension <> ".suo" OrElse fileExtension <> ".ini" Then
    11.                 ' handle here
    12.             End If
    13.         Next
    14.     End Sub
    15.  
    16. End Class

    An alternative way using LINQ

    vb Code:
    1. Option Strict On
    2.  
    3. Imports System.IO
    4.  
    5. Public Class Form1
    6.  
    7.     Private Sub Foo(ByVal path As String)
    8.         Dim files = Directory.GetFiles(path).Where(Function(f) GetExtension(f) <> ".suo" OrElse GetExtension(f) <> ".ini").ToArray
    9.  
    10.         Me.TextBox1.Text = files.Count.ToString
    11.  
    12.         For Each currentFile In files
    13.             ' handle here
    14.         Next
    15.     End Sub
    16.  
    17.     Private Function GetExtension(ByVal file As String) As String
    18.         Return Path.GetExtension(file)
    19.     End Function
    20.  
    21. End Class


    If we are going to be using LINQ it feels better suited using EnumerateFiles.

    The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

    vb Code:
    1. Option Strict On
    2.  
    3. Imports System.IO
    4.  
    5. Public Class Form1
    6.  
    7.     Private Sub Foo(ByVal path As String)
    8.         For Each currentFile In Directory _
    9.             .GetFiles(path, "*", SearchOption.AllDirectories) _
    10.             .Where(Function(f) GetExtension(f) <> ".suo" OrElse GetExtension(f) <> ".ini")
    11.  
    12.             ' do what ever
    13.  
    14.         Next
    15.     End Sub
    16.  
    17.     Private Function GetExtension(ByVal file As String) As String
    18.         Return Path.GetExtension(file)
    19.     End Function
    20.  
    21. End Class

    Finally dont be using KILL, it is a carry on from even way back as D.O.S, use net methods such as io.file.delete method.

  6. #6
    Member
    Join Date
    Mar 2014
    Posts
    54

    Re: VB.NET - Search directories, subdirectories for files, excluding files by name or

    I have been trying to write this code for a little while now.. I need it to take a users search criteria and show the folder or files in an windows explorer window. Any Help

  7. #7
    New Member
    Join Date
    Jul 2015
    Posts
    1

    Re: VB.NET - Delete files in directory and subdirectories, excluding select extension

    Oh Peter Porter how I wish there was a warning on that codeblock heh.

    I was scrolling down and saw the Kill for every item in directories - well most every

    I do realize it's source for this task

    but- considering the consequences? Maybe we should add a warning?

    Since that code will wipe your drive from what I see

    I'd comment out the kill line maybe.

    Anyway heh- what can I say- YIKES.

    Tim Miltz

  8. #8

    Thread Starter
    Fanatic Member Peter Porter's Avatar
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    538

    Re: VB.NET - Delete files in directory and subdirectories, excluding select extension

    Hi, tfmiltz.

    I wrote this back in 2013 when I was a newbie to coding. Corrected...
    Last edited by Peter Porter; Jul 20th, 2015 at 09:41 AM.

  9. #9

    Thread Starter
    Fanatic Member Peter Porter's Avatar
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    538

    Re: VB.NET - Search directories, subdirectories for files, excluding files by name or

    ident, I know this thread is old, but thanks for the tips!

  10. #10
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,582

    Re: VB.NET - Search directories, subdirectories for files, excluding files by name or

    Well, the thread is even older now, but I came across it while searching and since I haven't really used LINQ I was examining ident's code to see if I could understand just what it was doing, in particular the "Where" extension function.
    Code:
                .Where(Function(f) GetExtension(f) <> ".suo" OrElse GetExtension(f) <> ".ini")
    I gathered from the thread that Peter's code was to skip processing .suo and .ini files, but ident was using the OrElse (essentially Or operation).
    Using Or to me would seem wrong, i.e.
    If the file ended in .suo, then the second expression would be True (the file wouldn't end in .ini) so the conditional code would be executed.
    Likewise, if the file ended in .ini, then the first expression (it doesn't end with .suo) would be true so the conditional code would be executed.

    So the filter isn't really filtering any files. The only way it could filter a file is if it ended with both .ini and .suo which isn't possible.
    I did a quick test to confirm the .ini and .suo files did get processed along with all other files in the directory.

    The condition needs to be And (i.e. AndAlso for the short circuit version). We want to process the file if it isn't a .suo file and it isn't a .ini file.
    Code:
            .Where(Function(f) GetExtension(f) <> ".suo" AndAlso GetExtension(f) <> ".ini")
    That will filter both .suo files and .ini files from being processed.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width