0

I am trying to find all .txt files within "C:\test" and sub directories.

At the moment I have managed to make it search for .txt files within the top layer of my documents.

Public Class Form1
  Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    'Dim path As String = "C:\\"
    Dim txt As String = "*.txt"

    For Each foundFile As String In My.Computer.FileSystem.GetFiles(
      My.Computer.FileSystem.SpecialDirectories.MyDocuments,
      FileIO.SearchOption.SearchAllSubDirectories, txt)

      ListBox1.Items.Add(foundFile)
    Next


  End Sub
End Class

I want something like:

My.Computer.FileSystem.path,
FileIO.SearchOption.SearchAllSubDirectories, txt)

The search all sub directories doesn't work for some unknown reason.

user692942
  • 16,398
  • 7
  • 76
  • 175
SamCramphorn
  • 143
  • 1
  • 2
  • 14
  • Do you get any exception? I tried your code with path="C:\" and it worked but I got an `UnauthorizedAccessException` in some windows system directory. – Alex B. Jan 21 '16 at 12:31
  • Can you show your code please? – SamCramphorn Jan 21 '16 at 12:34
  • So I tried with exactly your code having `path="C:\Test"`. I created some sub directories in it and some text files. Working as expected for me. – Alex B. Jan 21 '16 at 12:35
  • `Sub Main() Dim path As String = "C:\Test" Dim txt As String = "*.txt" For Each foundFile As String In My.Computer.FileSystem.GetFiles( path, FileIO.SearchOption.SearchAllSubDirectories, txt) System.Console.WriteLine(foundFile) Next End Sub` – Alex B. Jan 21 '16 at 12:37
  • Thanks Alex, this worked out great, however I can't search all subdirectories from C:\. – SamCramphorn Jan 21 '16 at 12:45
  • 1
    You need to run as administartor to search c: – Ahh ... It's a programming thi Jan 21 '16 at 12:51
  • What do you mean with `I can´t search ...` ? Do you get any exceptions ? What is the actual result? As I wrote eralier you will get `UnauthorizedAccessException` for folders you have no read rights for. – Alex B. Jan 21 '16 at 12:53
  • @AlexB. It doesn't show the results. For example I will search for *.txt files. The first folder in C:\ is 'AAA' within that is a txt. It won't show it though. – SamCramphorn Jan 21 '16 at 12:55
  • As @Someonethatmatters wrote, try executing your program with admin privileges – Alex B. Jan 21 '16 at 12:58

2 Answers2

2

The Directory class (from System.IO namespace) has the method required and you don't need the For Each loop

Dim path As String = "C:\test"
Dim txt As String = "*.txt"

ListBox1.Items.AddRange(Directory.EnumerateFiles(path, txt, SearchOption.AllDirectories ).ToArray())           

Keep in mind that any tentative to read reserved file system folders like C:\System Volume Information will result in a UnauthorizedAccessException so, if your path variable is dynamic, then be prepared to catch eventually any exception raised by this call

EDIT

This is the conversion in VB.NET of the procedure shown by Mr Gravell in this question where he explains a method to traverse all the directories from the root of the system drive without stopping at the exceptions thrown by certain system folders (like System Volume Information or Program)

Delegate Sub ProcessFileDelegate(ByVal path As String)

Sub Main
    Dim path = "c:\"
    Dim ext = "*.txt"
    Dim runProcess As ProcessFileDelegate = AddressOf ProcessFile
    ApplyAllFiles(path, ext, runProcess)
End Sub

Sub ProcessFile(ByVal path As String)
    ' This is the sub where you process the filename passed in'
    ' you add it to your listbox or to some kind of collection '
    ListBox1.Items.Add(path)
End Sub

' This is the recursive procedure that traverse all the directory and'
' pass each filename to the delegate that adds the file to the listbox'
Sub ApplyAllFiles(ByVal folder As String, ByVal extension As String, ByVal fileAction As ProcessFileDelegate)
    For Each file In Directory.GetFiles(folder, extension)
        fileAction.Invoke(file)
    Next    
    For Each subDir In Directory.GetDirectories(folder)
        Try
            ApplyAllFiles(subDir, extension, fileAction)
        Catch ex As Exception
            ' Console.WriteLine(ex.Message)'
            ' Or simply do nothing '
        End Try
    Next

End Sub
Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Do I need to declare this as I am returning an error, Directory is not declared & SearchOption – SamCramphorn Jan 21 '16 at 12:48
  • Yes you need the Imports System.IO – Steve Jan 21 '16 at 12:48
  • Thanks Steve, this works fine but I can't do it form C:\ (it may not be .txt files I want to search for.) – SamCramphorn Jan 21 '16 at 12:50
  • 1
    As I have said in the answer, certain path raises an AccessUnauthorized exception because the SO blocks any access to these folders for security concerns. If you set AllDirectories and start from the C: root you are inevitably matching this problem – Steve Jan 21 '16 at 12:56
  • Is there a way to only search un-hidden folders? i.e. the ones that the user can see. EDIT Alternatively, if an error occurs ignore that path and search next one? – SamCramphorn Jan 21 '16 at 13:00
  • Then this question/answer probably will be of help http://stackoverflow.com/questions/172544/ignore-folders-files-when-directory-getfiles-is-denied-access – Steve Jan 21 '16 at 13:27
  • Thanks Steve although this is VB not C# – SamCramphorn Jan 21 '16 at 13:31
  • Sorry, but now I haven't enough time to translate it to VB. Later perhaps – Steve Jan 21 '16 at 13:50
  • if you could that would be great. I used http://converter.telerik.com/ but I am not sure how accurate that really is. – SamCramphorn Jan 21 '16 at 13:59
  • OK found the time to convert that code. It has been enlightening – Steve Jan 21 '16 at 19:27
  • Thanks Steve, great stuff! How do I now execute this? – SamCramphorn Jan 22 '16 at 09:28
  • When you need to list the files with a certain extension? I don't know what your whole program does – Steve Jan 22 '16 at 10:16
  • Then create the event handler for your button click event and call ApplyAllFiles after parameterizing the path and the extension (probably reading some textbox?) – Steve Jan 22 '16 at 10:58
  • Yep, I want the values to paste into listbox1 as items. – SamCramphorn Jan 22 '16 at 11:13
0

you can try with

Directory.GetFiles("searchpath", "extension")

instead of

My.Computer.FileSystem.GetFiles()
Dandy
  • 467
  • 1
  • 10
  • 33