שתף באמצעות


VB.net Find files and folders in folder and subfolder works in one folder but not in another

Question

Sunday, November 6, 2016 6:28 PM

Hi,
As an autodidact I am trying to get the hang of VB.net.
Wrote some code to search file and folders in folder and subfolders, and write result to a Listbox.
This works great for a Folder on C drive

But On other folders It doesn't.
I have lookes ad pemissions ans set them all ( admin, system, user) to full control.
So the code works, but not on every folder and subfolders.
What is going on ?

Here the code I use to recursivly go through the folder structure

Imports System.IO

Public Class Form1
    Dim R As IO.StreamReader
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListBox1.Items.Clear()
        Me.FolderBrowserDialog1.ShowDialog()
        Listfiles(Me.FolderBrowserDialog1.SelectedPath)
    End Sub

    Public Sub Listfiles(ByVal Pad As String)

        Dim DirInfo As New IO.DirectoryInfo(Pad)
        Dim FileObject As IO.FileSystemInfo
        Dim strBESTAND As String


        For Each FileObject In DirInfo.GetFileSystemInfos
            'Als FileObject een map is dan
            If FileObject.Attributes = IO.FileAttributes.Directory Then             '

                'Hier vind je alle mappen en submappen
                Listfiles(FileObject.FullName)
                Me.ListBox1.Items.Add(FileObject.FullName)
            Else
                strBESTAND = (FileObject.FullName)

                Dim information = My.Computer.FileSystem.GetFileInfo(strBESTAND)

                ' Áls extentie overeen komt ..........
                Dim strEXTENTIE As String
                'Als extentie in checkedlistbox aangevinkt is
                For i As Integer = 0 To (CheckedListBoxEXTENTIES.CheckedItems.Count - 1)  ' iterate on checked items
                    'Gebruik alleen de aangevinkte opties
                    strEXTENTIE = ((CheckedListBoxEXTENTIES.GetItemText(CheckedListBoxEXTENTIES.CheckedItems(i)).ToString))
                    If information.Extension = "." & strEXTENTIE Then
                        strBESTAND = information.Name
                        Me.ListBox1.Items.Add(FileObject.Name)

                    End If
                Next
            End If
        Next
        MessageBox.Show("Done!")
    End Sub

I am just dabling with VB.net so therre is no presure,but I do want to know why this happens

Thanks ,

Case Clay

All replies (25)

Tuesday, November 8, 2016 5:30 AM ✅Answered

it6:27 been at it all night
Got the thing working :D
Tahnx all for thinking with me, and giving tips

This is what i did in the end

    Sub DirSearch(ByVal sDir As String)
        Dim FileObject As IO.FileSystemInfo
        Dim DirInfo As New IO.DirectoryInfo(sDir)
        Dim strDirectory As String
        Dim strFile As String

        Try
            For Each strDirectory In Directory.GetDirectories(sDir)
                ListBox1.Items.Add(strDirectory)
                Dim strEXTENTIE As String
                'Als extentie in checkedlistbox aangevinkt is
                For i As Integer = 0 To (CheckedListBoxEXTENTIES.CheckedItems.Count - 1)  ' iterate on checked items
                    'Gebruik alleen de aangevinkte opties
                    strEXTENTIE = ((CheckedListBoxEXTENTIES.GetItemText(CheckedListBoxEXTENTIES.CheckedItems(i)).ToString))
                    'Elk bestand met de juiste extentie
                    For Each strFile In Directory.GetFiles(strDirectory, "*.*" & strEXTENTIE)
                        'Bestand naar listbox schrijven
                        Dim information = My.Computer.FileSystem.GetFileInfo(strFile)
                        strFile = (information.Name)

                        ListBox1.Items.Add(strFile)
                    Next
                Next
                'voer de sub nog een keer uit
                DirSearch(strDirectory)
            Next
        Catch ex As System.Exception
            Debug.WriteLine(ex.Message)
        End Try

    End Sub

Case Closed I guess :D

Knowledge is progres


Sunday, November 6, 2016 6:36 PM

g,

You might want to stick to some basics here - for example, if you'll look at the IO.Directory class, you'll see there are several methods that you can use directly.

For example to get directories (sub-directories), you might want to use the .EnumerateDirectories method (which is overloaded). To get files from a particular directory, you can use the .EnumerateFiles method which is also overloaded.

There's also the GetDirectories and GetFiles methods which is similar so be sure to read the documentation.

One thing to be aware of though: If you run into an UnauthorizedAccessException, that needs to be dealt with in a special way, but you didn't ask about that, so - I'll leave it that. :)

"Everybody in this country should learn how to program a computer... because it teaches you how to think." (Steve Jobs)


Sunday, November 6, 2016 6:38 PM

There are some files that are restricted to access by your user account. This may be a cause.

I have written a drive searcher if you want to take a look, visit this link:

MSDN Code Gallery - Drive Searcher


Don't forget to vote for Helpful Posts and Mark Answers!
*This post does not reflect the opinion of Microsoft, or its employees.


Sunday, November 6, 2016 6:38 PM

Try a different way of detecting directories:

*  If ( FileObject.Attributes And FileAttributes.Directory ) <> 0 Then
    . . .*

Also consider a case-insensitive filtering of extensions.


Sunday, November 6, 2016 7:14 PM

I am learning as I go, no teacher or something, lot of searching the net for code.
Have to figure out what al those lines of code mean and do.
So find a snippet, check what it does and why, implement in code.
I have not read or understood the methods, I check MSDN and see al te methods etc a class can have, and try to find one I can use.

You guys are way ahead of me ;)

Recently started ( 3 days ago)

This is ment to , when I am finished renaming mp3 and flac file to get standard filenames
Foldername is
Artist - Album

Filename is
Artist - tracknumber - Song. extention

When that is done, I want to do recursive search, cut strings in semistrings, an d write all files to excel.
Sheets atoz
1ste letter of artist name desides what sheet wil be used.

So I got my work cut out for me. It is just a hobby thing to get me through the winter. I don't work anymore and got to fill my days.

Lots of reading to do
Thanks everyone for the replies

Knowledge is progres


Sunday, November 6, 2016 7:16 PM

user has full control ( ex system engineer so know about that kind of things, was 1st thing I checked and changed)

Knowledge is progres


Sunday, November 6, 2016 7:17 PM

I get extentions from a checkedlistbox, and they are all lower case

Knowledge is progres


Sunday, November 6, 2016 8:34 PM

I am learning as I go, no teacher or something, lot of searching the net for code.
Have to figure out what al those lines of code mean and do.
So find a snippet, check what it does and why, implement in code.
I have not read or understood the methods, I check MSDN and see al te methods etc a class can have, and try to find one I can use.

You guys are way ahead of me ;)

Recently started ( 3 days ago)

This is ment to , when I am finished renaming mp3 and flac file to get standard filenames
Foldername is
Artist - Album

Filename is
Artist - tracknumber - Song. extention

When that is done, I want to do recursive search, cut strings in semistrings, an d write all files to excel.
Shaats atoz
!ste letter of artist name desides what sheet wil be used.

So I got my work cut out for me. It is just a hobby thing to get me through the winter. I don't work anymore and got to fill my days.

Lots of reading to do
Thanks everyone for the replies

Knowledge is progres

Well perhaps you should start by learning rather than coding things which may not end up what they should be.

MSDN Library search engine

Visual Basic

How to start programming videos

The New Boston videos

Getting started tutorials - Hands on step by step

VB Helper - Select the "Index" link on the left side of the page. under "Home" and you will find many helpful areas.

Also Windows security may allow a non-admin app to access certain locations (directories, folders, files) on a system, an app running with admin privilieges under a specific user to access certain locations (more than an app not running with admin priviliges) but not all locations can be accessed since some locations the system will not allow to be accessed by an app even if it is running with admin privileges. In order to keep even an admin user from destroying things beyond repair if possible. And to try to keep viruses that somehow get on a system that even achieved admin capability from destroying a system if possible.

La vida loca


Sunday, November 6, 2016 9:04 PM

Thanx for the links.
Been playing with VB6 in the past, and made the same app as I am trying to make now.
DotNet is the same but different, so to say
And there is a lot to take in, I get lost in all the things there are to know.
So I try to pick what I need a,d read accordingly
But The new boston looks prommissing, thanx again.

Knowledge is progres


Sunday, November 6, 2016 10:15 PM

Thanx for the links.
Been playing with VB6 in the past, and made the same app as I am trying to make now.
DotNet is the same but different, so to say
And there is a lot to take in, I get lost in all the things there are to know.
So I try to pick what I need a,d read accordingly
But The new boston looks prommissing, thanx again.

Knowledge is progres

 It just so happens that i have been working on an example code today for a question on another forum that finds the number of files,  number of folders,  and the total size of all the files of a given directory.  It iterates through all the sub folders under the given directory to do this.

 So, just to show an example of what has been said about running the app with or without admin privileges and the files/folders it will find,  below is 2 images of the app after iterating through the C:\Windows directory,  the first was ran without admin privileges and the second image is when it was ran with admin privileges.  You can see it finds more when it has admin privileges.

 However,  even with admin privileges,  i know it still can not access all of the folders/files.   8)

  

 

If you say it can`t be done then i`ll try it


Sunday, November 6, 2016 11:12 PM

Hi,
As an autodidact I am trying to get the hang of VB.net.
Wrote some code to search file and folders in folder and subfolders, and write result to a Listbox.
This works great for a Folder on C drive

But On other folders It doesn't.
I have lookes ad pemissions ans set them all ( admin, system, user) to full control.
So the code works, but not on every folder and subfolders.
What is going on ?

Here the code I use to recursivly go through the folder structure

Imports System.IO

Public Class Form1
    Dim R As IO.StreamReader
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListBox1.Items.Clear()
        Me.FolderBrowserDialog1.ShowDialog()
        Listfiles(Me.FolderBrowserDialog1.SelectedPath)
    End Sub

    Public Sub Listfiles(ByVal Pad As String)

        Dim DirInfo As New IO.DirectoryInfo(Pad)
        Dim FileObject As IO.FileSystemInfo
        Dim strBESTAND As String


        For Each FileObject In DirInfo.GetFileSystemInfos
            'Als FileObject een map is dan
            If FileObject.Attributes = IO.FileAttributes.Directory Then             '

                'Hier vind je alle mappen en submappen
                Listfiles(FileObject.FullName)
                Me.ListBox1.Items.Add(FileObject.FullName)
            Else
                strBESTAND = (FileObject.FullName)

                Dim information = My.Computer.FileSystem.GetFileInfo(strBESTAND)

                ' Áls extentie overeen komt ..........
                Dim strEXTENTIE As String
                'Als extentie in checkedlistbox aangevinkt is
                For i As Integer = 0 To (CheckedListBoxEXTENTIES.CheckedItems.Count - 1)  ' iterate on checked items
                    'Gebruik alleen de aangevinkte opties
                    strEXTENTIE = ((CheckedListBoxEXTENTIES.GetItemText(CheckedListBoxEXTENTIES.CheckedItems(i)).ToString))
                    If information.Extension = "." & strEXTENTIE Then
                        strBESTAND = information.Name
                        Me.ListBox1.Items.Add(FileObject.Name)

                    End If
                Next
            End If
        Next
        MessageBox.Show("Done!")
    End Sub

I am just dabling with VB.net so therre is no presure,but I do want to know why this happens

Thanks ,

Case Clay

I found an interesting article for you.

Is a good point to start with

http://glassocean.net/how-to-create-a-treeview-file-browser-component-in-vb-net-part-2/


Monday, November 7, 2016 8:17 AM

Thanx Appie or dank je wel ;)

Knowledge is progres


Monday, November 7, 2016 8:36 AM

thnx for the reply,

I understand that not all folders are accessible in C:\Windows ( not even as a admin).
But that is not he case in my prob.
Folders are  for example : "C:\ A Folder\An Other Folder"  or "D:\a Folder" etc.
And I have set the privileges of users and system to full control ( under laying items inherit permissions from this folder) just to make sure I avoid UnauthorizedAccessException.

So why does the code work on one folder and not another folder?

After lying awake half the night pondering I thought of this:
I am thinking in the line of whom the folder was created by ( of course I created the testfolder, and the subfolders within)
  I a copied folder ( which I did not create) to the testfolder is not found by the code.

I have set permissions ( again) to full control, but it has no effect.
If this assumption is correct( If not created by me, folder is not processed), how to tackle the problem?

Gaver

Knowledge is progress


Monday, November 7, 2016 8:39 AM

Hi,

there also was an example called "Create an Explorer style Application" in the very first .net samples (101 .net samples) that used a treeview.

https://www.microsoft.com/en-us/download/details.aspx?id=4856

Regards,

  Thorsten


Monday, November 7, 2016 10:15 AM

Thank!


Monday, November 7, 2016 10:35 AM

Ah nice one, thanx :D Thorsten.

Knowledge is progres


Monday, November 7, 2016 11:44 AM

Ok, Found the example called "Create an Explorer style Application" and used it.
I got this

The attributes for 1973 - Ring Ring and SubLayer 1 are both A ( archive)
  If I run prog this is what shows up in listbox

I started a new,( new project to get ride of all the excess lines of code.)

I hardcoded the path into TextBoxGevondenFolder.Text for now.

  Private Sub btnZoekMsppen_Click(sender As Object, e As EventArgs) Handles btnZoekMsppen.Click
        ListBoxGevondenFolders.Items.Clear()
        Dim di As DirectoryInfo = New DirectoryInfo(TextBoxGevondenFolder.Text) '=C:\!TestFolder
        Try
            ' Determine whether the directory exists.
            If di.Exists Then
                ' Indicate that it already exists.
                Listfolders(Me.TextBoxGevondenFolder.Text)
                GroupBoxGevondenItems.Text = "Deze mappen zijn gevonden in" & TextBoxGevondenFolder.Text
                MessageBox.Show("Done!")
                Return
            End If
        Catch ex As Exception
            MessageBox.Show("The process failed: {0}", e.ToString())
        End Try
    End Sub
    Public Sub Listfolders(ByVal Pad As String)

        Dim DirInfo As New IO.DirectoryInfo(Pad)
        Dim FileObject As IO.FileSystemInfo
        Dim strBESTAND As String

        For Each FileObject In DirInfo.GetFileSystemInfos

            If FileObject.Attributes = IO.FileAttributes.Directory Then
                'Fileobject is Folder
                Listfolders(FileObject.FullName)
                Me.ListBoxGevondenFolders.Items.Add(FileObject.FullName)
            Else
                'Fileobject is file
                strBESTAND = (FileObject.FullName)
                Dim information = My.Computer.FileSystem.GetFileInfo(strBESTAND)
                strBESTAND = information.Name
                Me.ListBoxGevondenFolders.Items.Add(FileObject.Name)
            End If
        Next
    End Sub
End Class

As You can see, the folder 1973 - Ring Ring is found, but not the files in the folder.

The folder "Sublayer1" is found and the file within "SubLayer 1 folder - test.txt" is also found.Same goes for folder "Sublayer2" and the file within "SubLayer 2 folder - test.txt"

If I use the 1973 - Ring Ring folder to start the search in, I do get the files within listed.

below the permission settings ( They are identical)

Why are files and folder in Sublayer 1 found, but not in 1973 - Ring Ring?
As far as I can tell, there is no difference between the folders.( except who created them)

If it is caused by the creator, how to fix this?

ps

I have tried various folders on various drives to see what happens.
There are folders created by me, with subfolders created by me, but the listing consists of folders and files  in searchfolder, without listing of items in subfolders.

I tried "C:\Users\kees\Pictures" ( My documents) and got all within( files and subfolders and files in subfolders).

Gaver

Knowledge is progres


Monday, November 7, 2016 4:33 PM

Ok, Found the example called "Create an Explorer style Application" and used it.
I got this

The attributes for 1973 - Ring Ring and SubLayer 1 are both A ( archive)
  If I run prog this is what shows up in listbox

I started a new,( new project to get ride of all the excess lines of code.)

I hardcoded the path into TextBoxGevondenFolder.Text for now.

  Private Sub btnZoekMsppen_Click(sender As Object, e As EventArgs) Handles btnZoekMsppen.Click
        ListBoxGevondenFolders.Items.Clear()
        Dim di As DirectoryInfo = New DirectoryInfo(TextBoxGevondenFolder.Text) '=C:\!TestFolder
        Try
            ' Determine whether the directory exists.
            If di.Exists Then
                ' Indicate that it already exists.
                Listfolders(Me.TextBoxGevondenFolder.Text)
                GroupBoxGevondenItems.Text = "Deze mappen zijn gevonden in" & TextBoxGevondenFolder.Text
                MessageBox.Show("Done!")
                Return
            End If
        Catch ex As Exception
            MessageBox.Show("The process failed: {0}", e.ToString())
        End Try
    End Sub
    Public Sub Listfolders(ByVal Pad As String)

        Dim DirInfo As New IO.DirectoryInfo(Pad)
        Dim FileObject As IO.FileSystemInfo
        Dim strBESTAND As String

        For Each FileObject In DirInfo.GetFileSystemInfos

            If FileObject.Attributes = IO.FileAttributes.Directory Then
                'Fileobject is Folder
                Listfolders(FileObject.FullName)
                Me.ListBoxGevondenFolders.Items.Add(FileObject.FullName)
            Else
                'Fileobject is file
                strBESTAND = (FileObject.FullName)
                Dim information = My.Computer.FileSystem.GetFileInfo(strBESTAND)
                strBESTAND = information.Name
                Me.ListBoxGevondenFolders.Items.Add(FileObject.Name)
            End If
        Next
    End Sub
End Class

As You can see, the folder 1973 - Ring Ring is found, but not the files in the folder.

The folder "Sublayer1" is found and the file within "SubLayer 1 folder - test.txt" is also found.Same goes for folder "Sublayer2" and the file within "SubLayer 2 folder - test.txt"

If I use the 1973 - Ring Ring folder to start the search in, I do get the files within listed.

below the permission settings ( They are identical)

Why are files and folder in Sublayer 1 found, but not in 1973 - Ring Ring?
As far as I can tell, there is no difference between the folders.( except who created them)

If it is caused by the creator, how to fix this?

ps

I have tried various folders on various drives to see what happens.
There are folders created by me, with subfolders created by me, but the listing consists of folders and files  in searchfolder, without listing of items in subfolders.

I tried "C:\Users\kees\Pictures" ( My documents) and got all within( files and subfolders and files in subfolders).

Gaver

Knowledge is progres

Since the example was written by somebody else you should contact them with issues about their example especially if you altered code in it.

La vida loca


Monday, November 7, 2016 5:52 PM

I started anew again.

Used minimal amount of code, and commented in English.
Kept the names of the elements on the form standard.

Used msgboxes to see what is happening, and found something funny.
As you can see above in the folderstructure "1973 - Ring Ring" is a folder.
The code sees it as  a File, and therefore does not search it.
The other subfolders are seen as Folders though.

Imports System.IO
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListBox1.Items.Clear()
        Listfolders(TextBox1.Text) 'Call Public Sub ListFolders
        'If i would put code here, search isn't recursive
    End Sub
    Public Sub Listfolders(ByVal Path As String) 'Path is Texbox1.Text

        Dim DirInfo As New IO.DirectoryInfo(Path) 'C:\!Testfolder
        Dim FileObject As IO.FileSystemInfo

        For Each FileObject In DirInfo.GetFileSystemInfos 'fileobject is file or folder
            If FileObject.Attributes = IO.FileAttributes.Directory Then
                'Fileobject is Folder
                Listfolders(FileObject.FullName) 'Use public Sub again to find folders and files in subfolders
                MessageBox.Show("This must be the whole path>> " & FileObject.FullName)
                MessageBox.Show("This must be a Folder>> " & FileObject.Name)
                ListBox1.Items.Add(FileObject.Name) 'Add folder to listbox
            Else
                'Fileobject is file
                MessageBox.Show("This must be a File>> " & FileObject.Name)
                ListBox1.Items.Add(FileObject.Name) 'Add file to listbox
            End If
        Next

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        TextBox1.Text = "C:\!TestFolder" 'Give initial text to Textbox1
    End Sub
End Class

Why is this happening?
Sorry if I keep at it, but it is not logical :(
Thnx, Gaver

Knowledge is progress


Monday, November 7, 2016 8:22 PM

If you are 100% sure that this is not permissions, try something like this:

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim StartFolder As String = ""
        Dim AllFiles As New List(Of String)
        Using fbd As New FolderBrowserDialog
            If fbd.ShowDialog = Windows.Forms.DialogResult.OK Then
                StartFolder = fbd.SelectedPath
            End If
        End Using
        If IO.Directory.Exists(StartFolder) Then
            AllFiles.AddRange(My.Computer.FileSystem.GetFiles(StartFolder, FileIO.SearchOption.SearchAllSubDirectories))
            For Each filename As String In AllFiles
                TextBox1.AppendText(filename & vbNewLine)
            Next
        End If
    End Sub
End Class

Very crude, no error checking, takes a long time if there are many many files, for concept only.


Monday, November 7, 2016 8:41 PM

Hi Devon,

I want to use this to archive my Music folder to Excel, so strings will be cut up to separate artist, tracknumber, song, extention. foldername ( = albumname+ year+ bitrate)
All will go into separate column.

Got roughly a terra of music aboard, so if you are correct it will take forever youre code will only list files'.

What I do not get, is why is a folder seen as a file?

Knowledge is progres


Monday, November 7, 2016 9:31 PM

This code here contains the correct method FileSystemInfo.Attributes Property for determining if a path is for a Directory or File really.

La vida loca


Monday, November 7, 2016 11:03 PM

thanx, gotta read this a few times to figure it out and implement in code .
More food for thought ;)

Gaver

Knowledge is progres


Tuesday, November 8, 2016 2:19 AM

 A File or Folder can have more than 1 attribute added to it.  If your directory has any other attributes added to it along with the Directory attribute such as the System attribute for example,  the attribute would not be equal to the Directory attribute.  The FileAttributes are Integer type flags that are added together so,  you would need to use the And bitwise operator to check if the Attributes contain a specific attribute.

 Try changing this line...

If FileObject.Attributes = IO.FileAttributes.Directory Then

 

 To this...

If (FileObject.Attributes And IO.FileAttributes.Directory) = IO.FileAttributes.Directory Then

 

If you say it can`t be done then i`ll try it


Wednesday, November 9, 2016 7:29 AM

Hi gavertje,

Glad to hear this issue has been solved by yourself. Thanks for your sharing, I will introduce this experience to other forum users who face the same condition. Please remember to close your thread by marking your reply and then start a new thread if you have a new question.

Thank you for participating in the forum activities.

Best Regards,

Neda Zhang

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.