none
Count # of files matching a pattern RRS feed

  • Question

  • Hello, I am converting an old vb6 utility that counts the number of files in a directory that matches a specific pattern. So far, I have not been able to figure it out. Can someone guide me in the right direction?
    Thursday, July 28, 2016 12:00 PM

Answers

  • Hello,

    Please describe the pattern e.g. by extension, by specific characters in the base file name etc.

    In the mean time something to get you on track

    Dim Files As String() = Directory.GetFiles("C:\Data", "*.*", SearchOption.TopDirectoryOnly)
    
    For Each file As String In Files
        If Path.GetFileName(file).StartsWith("s", StringComparison.OrdinalIgnoreCase) Then
            Console.WriteLine($"Name: {IO.Path.GetFileName(file)} Ext: {Path.GetExtension(file)}")
        End If
    Next
    Console.WriteLine()
    Dim total As Integer = Files.Where(Function(file) Path.GetFileName(file).StartsWith("s", StringComparison.OrdinalIgnoreCase)).Count
    Console.WriteLine(total)
    Note, Directory.GetFiles is overloaded so check the method out in MSDN docs.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by SeaDevil664 Thursday, July 28, 2016 5:36 PM
    Thursday, July 28, 2016 12:43 PM
    Moderator
  • Hello, I am converting an old vb6 utility that counts the number of files in a directory that matches a specific pattern. So far, I have not been able to figure it out. Can someone guide me in the right direction?

    Hi

    Another example. Based on extension for pattern. Select folder, choose extension in combobox. This demo is only for one run - would need lots of changes to make it 'reusable' ie to choose a different folder.

    ' new project with blank default Form1
    Option Strict On
    Option Infer Off
    Option Explicit On
    Public Class Form1
        Dim lab1 As New Label
        Dim lb1 As New ListBox
        Dim cb As New ComboBox
        Dim files As ObjectModel.ReadOnlyCollection(Of String) = Nothing
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.Size = New Size(600, 360)
            ' set up controls
            With lab1
                .Text = "Folder"
                .Location = New Point(10, 10)
            End With
            With lb1
                .Location = New Point(10, 40)
                .Height = ClientRectangle.Height - 85
                .Width = (ClientRectangle.Width - 30)
                .Anchor = AnchorStyles.Right Or AnchorStyles.Top Or AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            With cb
                .Location = New Point(10, lb1.Bottom + 8)
                .Width = 120
                .Font = New Font("Arial", 14)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            Me.Controls.AddRange({lab1, lb1, cb})
    
    
            ' Choose folder to act on
            Dim fb As New FolderBrowserDialog
            With fb
                ' start in My Documents folder
                .RootFolder = Environment.SpecialFolder.MyDocuments
                ' disallow user create new folder
                .ShowNewFolderButton = False
            End With
            ' create a variable to hold user input
            Dim result As DialogResult
            ' show dialog and get user input
            result = fb.ShowDialog
    
            ' if user clicks OK button
            If result = DialogResult.OK Then
                ' fb.SelectedPath now holds user selected folder
    
            Else
                ' user didn't click OK button so no point in
                ' continuing this example
                End
            End If
    
            'OK here we have the selected folder
            ' so get a list of the files within
            files = My.Computer.FileSystem.GetFiles(fb.SelectedPath)
    
            ' make a list of extensions
            Dim exList As New List(Of String)
    
            For Each f As String In files
                Dim ex As String = IO.Path.GetExtension(f)
                If Not exList.Contains(ex) Then
                    exList.Add(ex)
                End If
            Next
    
            ' put extension list as combobox datasource
            cb.DataSource = exList
    
            ' add handler for combobox change selection
            AddHandler cb.SelectedIndexChanged, AddressOf Cb_SelectedIndexChanged
        End Sub
    
        Private Sub Cb_SelectedIndexChanged(sender As Object, e As EventArgs)
            Dim c As ComboBox = DirectCast(sender, ComboBox)
            Dim ex As String = c.SelectedItem.ToString
            ' clear and reset listbox contents to selected extensions
            lb1.Items.Clear()
            For Each s As String In files
                If s.EndsWith(ex) Then lb1.Items.Add(s)
            Next
        End Sub
    End Class


    Regards Les, Livingston, Scotland

    • Marked as answer by SeaDevil664 Thursday, July 28, 2016 5:35 PM
    Thursday, July 28, 2016 1:05 PM

All replies

  • Hello,

    Please describe the pattern e.g. by extension, by specific characters in the base file name etc.

    In the mean time something to get you on track

    Dim Files As String() = Directory.GetFiles("C:\Data", "*.*", SearchOption.TopDirectoryOnly)
    
    For Each file As String In Files
        If Path.GetFileName(file).StartsWith("s", StringComparison.OrdinalIgnoreCase) Then
            Console.WriteLine($"Name: {IO.Path.GetFileName(file)} Ext: {Path.GetExtension(file)}")
        End If
    Next
    Console.WriteLine()
    Dim total As Integer = Files.Where(Function(file) Path.GetFileName(file).StartsWith("s", StringComparison.OrdinalIgnoreCase)).Count
    Console.WriteLine(total)
    Note, Directory.GetFiles is overloaded so check the method out in MSDN docs.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by SeaDevil664 Thursday, July 28, 2016 5:36 PM
    Thursday, July 28, 2016 12:43 PM
    Moderator
  • Hello, I am converting an old vb6 utility that counts the number of files in a directory that matches a specific pattern. So far, I have not been able to figure it out. Can someone guide me in the right direction?

    Hi

    Another example. Based on extension for pattern. Select folder, choose extension in combobox. This demo is only for one run - would need lots of changes to make it 'reusable' ie to choose a different folder.

    ' new project with blank default Form1
    Option Strict On
    Option Infer Off
    Option Explicit On
    Public Class Form1
        Dim lab1 As New Label
        Dim lb1 As New ListBox
        Dim cb As New ComboBox
        Dim files As ObjectModel.ReadOnlyCollection(Of String) = Nothing
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.Size = New Size(600, 360)
            ' set up controls
            With lab1
                .Text = "Folder"
                .Location = New Point(10, 10)
            End With
            With lb1
                .Location = New Point(10, 40)
                .Height = ClientRectangle.Height - 85
                .Width = (ClientRectangle.Width - 30)
                .Anchor = AnchorStyles.Right Or AnchorStyles.Top Or AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            With cb
                .Location = New Point(10, lb1.Bottom + 8)
                .Width = 120
                .Font = New Font("Arial", 14)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            Me.Controls.AddRange({lab1, lb1, cb})
    
    
            ' Choose folder to act on
            Dim fb As New FolderBrowserDialog
            With fb
                ' start in My Documents folder
                .RootFolder = Environment.SpecialFolder.MyDocuments
                ' disallow user create new folder
                .ShowNewFolderButton = False
            End With
            ' create a variable to hold user input
            Dim result As DialogResult
            ' show dialog and get user input
            result = fb.ShowDialog
    
            ' if user clicks OK button
            If result = DialogResult.OK Then
                ' fb.SelectedPath now holds user selected folder
    
            Else
                ' user didn't click OK button so no point in
                ' continuing this example
                End
            End If
    
            'OK here we have the selected folder
            ' so get a list of the files within
            files = My.Computer.FileSystem.GetFiles(fb.SelectedPath)
    
            ' make a list of extensions
            Dim exList As New List(Of String)
    
            For Each f As String In files
                Dim ex As String = IO.Path.GetExtension(f)
                If Not exList.Contains(ex) Then
                    exList.Add(ex)
                End If
            Next
    
            ' put extension list as combobox datasource
            cb.DataSource = exList
    
            ' add handler for combobox change selection
            AddHandler cb.SelectedIndexChanged, AddressOf Cb_SelectedIndexChanged
        End Sub
    
        Private Sub Cb_SelectedIndexChanged(sender As Object, e As EventArgs)
            Dim c As ComboBox = DirectCast(sender, ComboBox)
            Dim ex As String = c.SelectedItem.ToString
            ' clear and reset listbox contents to selected extensions
            lb1.Items.Clear()
            For Each s As String In files
                If s.EndsWith(ex) Then lb1.Items.Add(s)
            Next
        End Sub
    End Class


    Regards Les, Livingston, Scotland

    • Marked as answer by SeaDevil664 Thursday, July 28, 2016 5:35 PM
    Thursday, July 28, 2016 1:05 PM
  • Hello, I am converting an old vb6 utility that counts the number of files in a directory that matches a specific pattern. So far, I have not been able to figure it out. Can someone guide me in the right direction?

    Would it be possible to provide some clues as to what that pattern might be ?
    The range of possibilities runs from all files with a filename containing "a" to all files where the name contains 2 or more vowels, 1 number, and does not contain "p" or "w", and is not a PDF or a GIF file (example only)

    The Directory.GetFiles method may be useful but be aware that if any error occurs, like an access denied error, the entire method fails. 

    Also, if using .NET 4.0 or higher, there is the Enumerate function here - read carefully, look at the examples for how to solve access errors.

    Lastly, there is code here to get a list of safe folders and files

    Thursday, July 28, 2016 1:08 PM
  • Directory.GetFiles Method (String, String, SearchOption)

    Option Strict On
    
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Label3.Text = "Waiting"
            Label3.Update()
            Using FBD As New FolderBrowserDialog
                With FBD
                    .SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
                    .ShowNewFolderButton = False
                    .Description = "Get file count for pattern."
                End With
                If TextBox1.Text <> "" Then
                    If FBD.ShowDialog = Windows.Forms.DialogResult.OK Then
                        If CheckBox1.Checked Then
                            Label3.Text = "File count is " & IO.Directory.GetFiles(FBD.SelectedPath, TextBox1.Text, IO.SearchOption.AllDirectories).Count.ToString
                        Else
                            Label3.Text = "File count is " & IO.Directory.GetFiles(FBD.SelectedPath, TextBox1.Text, IO.SearchOption.TopDirectoryOnly).Count.ToString
                        End If
                    End If
                End If
            End Using
        End Sub
    
    End Class
    


    La vida loca

    Thursday, July 28, 2016 5:59 PM