Results 1 to 8 of 8

Thread: [RESOLVED] Loading all files from folder that start with specific character

  1. #1

    Thread Starter
    PowerPoster Radjesh Klauke's Avatar
    Join Date
    Dec 2005
    Location
    Sexbierum (Netherlands)
    Posts
    2,244

    Resolved [RESOLVED] Loading all files from folder that start with specific character

    Heya,

    I'm loading a treeview with all files and folders. But how do I load only the files that start with (for example) "D".

    My current code (3rd party control):
    Code:
    Dim lnode As New Node("Exceptions")  ' create parentnode
       .Nodes.Add(lnode)  ' add parentnode to treeview
       For Each x In My.Computer.FileSystem.GetFiles(msopath)
          Dim n As New Node(Path.GetFileNameWithoutExtension(x.ToString))
          lnode.Nodes.Add(n)  ' add the filnames (and the image) to the parentnode
       Next
    Thanks in advance.


    If you found my post helpful, please rate it.

    Codebank Submission: FireFox Browser (Gecko) in VB.NET, Load files, (sub)folders treeview with Windows icons

  2. #2
    Still learning kebo's Avatar
    Join Date
    Apr 2004
    Location
    Gardnerville,nv
    Posts
    3,762

    Re: Loading all files from folder that start with specific character

    the get files method is overloaded so you can provide a filter pattern...
    Code:
    My.Computer.FileSystem.GetFiles(msopath, FileIO.SearchOption.SearchTopLevelOnly, {"d*.*"})
    or
    Code:
    My.Computer.FileSystem.GetFiles(msopath, FileIO.SearchOption.SearchAllSubDirectories, {"d*.*"})
    Process control doesn't give you good quality, it gives you consistent quality.
    Good quality comes from consistently doing the right things.

    Vague general questions have vague general answers.
    A $100 donation is required for me to help you if you PM me asking for help. Instructions for donating to one of our local charities will be provided.

    ______________________________
    Last edited by kebo : Now. Reason: superfluous typo's

  3. #3
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,714

    Re: Loading all files from folder that start with specific character

    What kebo suggested I think would be the best method to go with but if by chance you need for conditions met consider the following.

    Name:  11111PM.png
Views: 243
Size:  21.5 KB

    Code:
    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ComboBox1.DataSource = Enumerable.Range(0, 25).Select(Function(i) (Chr(Asc("A") + i))).ToList
        End Sub
        Private Sub Searcher(ByVal FolderName As String)
            Dim Dirs As IEnumerable(Of String) = Nothing
            Try
                Dim files() As String
                Dirs = IO.Directory.EnumerateDirectories(FolderName)
                files = IO.Directory.EnumerateFiles(FolderName) _
                    .Where(Function(CurrentFile As String)
                               Dim BaseName As String = IO.Path.GetFileName(CurrentFile).ToUpper
                               If BaseName.StartsWith(ComboBox1.Text) Then
                                   Return True
                               Else
                                   Return False
                               End If
                           End Function).ToArray
                ListBox1.Items.AddRange(files)
            Catch ex As Exception
                'Just Skip the denied access dirs
            End Try
            If Dirs IsNot Nothing Then
                For Each Dir As String In Dirs
                    Searcher(Dir)
                Next
            Else
                ' Access denied thrown in Catch above
            End If
        End Sub
        Private Sub cmdExecute_Click(sender As Object, e As EventArgs) Handles cmdExecute.Click
            If Not String.IsNullOrWhiteSpace(txtFolderName.Text) Then
                If IO.Directory.Exists(txtFolderName.Text) Then
                    Try
                        cmdExecute.Enabled = False
                        Application.DoEvents()
                        ListBox1.Items.Clear()
                        Searcher(txtFolderName.Text)
                    Finally
                        cmdExecute.Enabled = True
                    End Try
                Else
                    MessageBox.Show("Folder does not exists.")
                End If
            Else
                MessageBox.Show("Please enter a folder name")
            End If
        End Sub
    End Class

  4. #4
    Still learning kebo's Avatar
    Join Date
    Apr 2004
    Location
    Gardnerville,nv
    Posts
    3,762

    Re: Loading all files from folder that start with specific character

    I think the second overload in my first post will return files that match the criteria in all sub folders.
    Process control doesn't give you good quality, it gives you consistent quality.
    Good quality comes from consistently doing the right things.

    Vague general questions have vague general answers.
    A $100 donation is required for me to help you if you PM me asking for help. Instructions for donating to one of our local charities will be provided.

    ______________________________
    Last edited by kebo : Now. Reason: superfluous typo's

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

    Re: Loading all files from folder that start with specific character

    Quote Originally Posted by kebo View Post
    I think the second overload in my first post will return files that match the criteria in all sub folders.
    Then when the first directory throws access denied the code will not complete.
    My Github - 1d3nt

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

    Re: Loading all files from folder that start with specific character

    Ah its for a Treeview. I'm not going to include exception handling because you can modifie this bassed on Kevins exception handling.

    A previous example i posted.

    vb Code:
    1. Public Class Form1
    2.      
    3.         Private ReadOnly m_root As String = Environment.GetFolderPath(Environment.SpecialFolder.Favorites)
    4.      
    5.         Private Sub Form1_Load(ByVal sender As System.Object,
    6.                                ByVal e As System.EventArgs) Handles MyBase.Load
    7.             Dim rootNode As New TreeNode(Me.m_root, 0, 0, GetFavorites(Me.m_root))
    8.      
    9.             Me.TreeView1.Nodes.Add(rootNode)
    10.             Me.TreeView1.TopNode.Expand()
    11.         End Sub
    12.      
    13.         Private Function GetFavorites(ByVal folderPath As String) As TreeNode()
    14.             Dim nodes As New List(Of TreeNode)
    15.      
    16.             Array.ForEach(IO.Directory.GetDirectories(folderPath), Sub(t) nodes.Add(New TreeNode(IO.Path.GetFileName(t), 0, 0, GetFavorites(t))))
    17.             Array.ForEach(IO.Directory.GetFiles(folderPath), Sub(t) nodes.Add(New TreeNode(IO.Path.GetFileName(t), 1, 1)))
    18.      
    19.             Return nodes.ToArray()
    20.         End Function
    21.      
    22.         Private Sub TreeView1_NodeMouseDoubleClick(ByVal sender As Object, _
    23.                                                    ByVal e As TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseDoubleClick
    24.             Process.Start("iexplore.exe", DirectCast(e.Node, TreeNode).FullPath)
    25.         End Sub
    26.      
    27.     End Class
    My Github - 1d3nt

  7. #7
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,714

    Re: Loading all files from folder that start with specific character

    Quote Originally Posted by kebo View Post
    I think the second overload in my first post will return files that match the criteria in all sub folders.
    Yes it does and either of your suggestions should be used over mine unless there is a need for multiple conditions

    BTW the reason for my suggest was that multiple conditions could be done i.e. check base file name and base file name extension
    Code:
    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ComboBox1.DataSource = Enumerable.Range(0, 25).Select(Function(i) (Chr(Asc("A") + i))).ToList
            ComboBox2.DataSource = New List(Of String) From {".ACCDB", ".BMP", ".SQL"}
        End Sub
        Private Sub Searcher(ByVal FolderName As String)
            Dim Dirs As IEnumerable(Of String) = Nothing
            Try
                Dim files() As String
                Dirs = IO.Directory.EnumerateDirectories(FolderName)
                files = IO.Directory.EnumerateFiles(FolderName) _
                    .Where(Function(CurrentFile As String)
                               Dim BaseName As String = IO.Path.GetFileName(CurrentFile).ToUpper
                               '
                               ' Multiple conditions
                               '
                               If BaseName.StartsWith(ComboBox1.Text) AndAlso IO.Path.GetExtension(BaseName).ToUpper = ComboBox2.Text Then
                                   Return True
                               Else
                                   Return False
                               End If
                           End Function).ToArray
                ListBox1.Items.AddRange(files)
            Catch ex As Exception
                'Just Skip the denied access dirs
            End Try
            If Dirs IsNot Nothing Then
                For Each Dir As String In Dirs
                    Searcher(Dir)
                Next
            Else
                ' Access denied thrown in Catch above
            End If
        End Sub
        Private Sub cmdExecute_Click(sender As Object, e As EventArgs) Handles cmdExecute.Click
            If Not String.IsNullOrWhiteSpace(txtFolderName.Text) Then
                If IO.Directory.Exists(txtFolderName.Text) Then
                    Try
                        cmdExecute.Enabled = False
                        Application.DoEvents()
                        ListBox1.Items.Clear()
                        Searcher(txtFolderName.Text)
                    Finally
                        cmdExecute.Enabled = True
                    End Try
                Else
                    MessageBox.Show("Folder does not exists.")
                End If
            Else
                MessageBox.Show("Please enter a folder name")
            End If
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim Items = My.Computer.FileSystem.GetFiles(txtFolderName.Text, FileIO.SearchOption.SearchAllSubDirectories, {ComboBox1.Text & "*.*"})
            Console.WriteLine(Items.Count)
        End Sub
    
    End Class

  8. #8

    Thread Starter
    PowerPoster Radjesh Klauke's Avatar
    Join Date
    Dec 2005
    Location
    Sexbierum (Netherlands)
    Posts
    2,244

    Re: Loading all files from folder that start with specific character

    Thanks for all the input guys


    If you found my post helpful, please rate it.

    Codebank Submission: FireFox Browser (Gecko) in VB.NET, Load files, (sub)folders treeview with Windows icons

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