Solved

Recursive File Searching In VB.NET

Posted on 2009-05-07
19
436 Views
Last Modified: 2012-05-06
hello

i need help i am trying to search a folder on a coimputer with recursive searching i have a textfile with names like car,temp,money,popcorn and i want to go through each line of my file and fid it but my search app is broken can anyone help


CODE LISTED BELOW
Imports System
Imports System.Windows.Forms
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Collections.Specialized
Public Class Form1
    Dim currentDirectory As String = Directory.GetCurrentDirectory
    Dim directoryList As String()
    Dim fileArray As String()
    Dim found As NameValueCollection = New NameValueCollection()
 
    Public Sub New()
        MyBase.New()
 
        'This call is required by the Windows Form Designer.
        InitializeComponent()
 
        'Add any initialization after the InitializeComponent() call
 
    End Sub
 
    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
 
    Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click
        Dim current As String
 
 
        If txtInput.Text <> "" Then
 
            ' verify that user input is a valid directory name
            If Directory.Exists(txtInput.Text) Then
                currentDirectory = txtInput.Text
 
                ' reset input text box and update display
                lblDirectory.Text = "Current Directory:" & vbCrLf & _
                  currentDirectory
 
                ' show error if user does not specify valid directory
            Else
                MessageBox.Show("Invalid Directory", "Error", _
                   MessageBoxButtons.OK, MessageBoxIcon.Error)
 
                Return
            End If
 
        End If
 
        ' clear text boxes
        txtInput.Text = ""
        txtOutput.Text = ""
 
        ' search directory
        SearchDirectory(currentDirectory)
 
        ' summarize and print results
        For Each current In found
            txtOutput.Text &= "* Found " & found(current) & " " _
               & current & " files." & vbCrLf
        Next
 
        ' clear output for new search
        found.Clear()
    End Sub
    ' search directory using regular expression
    Private Sub SearchDirectory(ByVal currentDirectory As String)
 
        ' for file name without directory path
        Try
            Dim fileName As String = ""
            Dim myFile As String
            Dim myDirectory As String
 
            ' regular expression for extensions matching pattern
            Dim regularExpression As Regex = _
               New Regex("([a-zA-Z0-9]+\.(?<extension>\w+))")
 
            ' stores regular-expression-match result 
            Dim matchResult As Match
 
            Dim fileExtension As String ' holds file extensions
 
            ' number of files with given extension in directory
            Dim extensionCount As Integer
 
            ' get directories
            directoryList = _
               Directory.GetDirectories(currentDirectory)
 
            ' get list of files in current directory
            fileArray = Directory.GetFiles(currentDirectory)
 
            ' iterate through list of files
            For Each myFile In fileArray
 
 
                fileName = myFile.Substring( _
                   myFile.LastIndexOf("\") + 1)
 
 
                matchResult = regularExpression.Match(fileName)
 
 
                If (matchResult.Success) Then
                    fileExtension = matchResult.Result("${extension}")
                Else
                    fileExtension = "[no extension]"
                End If
 
 
                If (found(fileExtension) = Nothing) Then
                    found.Add(fileExtension, "1")
                Else
                    extensionCount = _
                       Convert.ToInt32(found(fileExtension)) + 1
 
                    found(fileExtension) = extensionCount.ToString()
                End If
 
 
            Next
 
 
            For Each myDirectory In directoryList
                SearchDirectory(myDirectory)
            Next
 
 
        Catch unauthorizedAccess As UnauthorizedAccessException
            MessageBox.Show("Some files may not be visible due to" _
               & " permission settings", "Warning", _
               MessageBoxButtons.OK, MessageBoxIcon.Information)
 
        End Try
 
    End Sub
 
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim path As String = "C:\Documents and Settings\joneschris\My Documents"
        Dim filters() As String = {"*.txt"}
        For Each file As String In My.Computer.FileSystem.GetFiles(path, FileIO.SearchOption.SearchAllSubDirectories, filters)
            ListBox1.Items.Add(file)
 
        Next
    End Sub
End Class

Open in new window

0
Comment
Question by:Chris Jones
  • 11
  • 5
  • 2
  • +1
19 Comments
 
LVL 9

Expert Comment

by:Deathrace
ID: 24327484
Did you see this, Excellent article from microsoft.
http://support.microsoft.com/kb/303974
0
 
LVL 1

Author Comment

by:Chris Jones
ID: 24327740
hello

i have converted and tested the code but it is locking up on my system


HERE IS THE CODE
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Data
Imports System.IO
Public Class Form1
 
    Friend btnSearch As System.Windows.Forms.Button
    Friend txtFile As System.Windows.Forms.TextBox
    Friend lblFile As System.Windows.Forms.Label
    Friend lblDirectory As System.Windows.Forms.Label
    Friend lstFilesFound As System.Windows.Forms.ListBox
    Friend cboDirectory As System.Windows.Forms.ComboBox
 
    Public Sub New()
        ' 
        ' Required for Windows Form Designer support 
        ' 
 
        ' 
        ' TODO: Add any constructor code after InitializeComponent call. 
        ' 
        InitializeComponent()
    End Sub
 
    ''' <summary> 
    ''' Clean up any resources being used. 
    ''' </summary> 
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If components IsNot Nothing Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
 
#Region "Windows Form Designer generated code"
    ''' <summary> 
    ''' Required method for Designer support: do not modify 
    ''' the contents of this method with the code editor. 
    ''' </summary> 
    Private Sub InitializeComponent()
        Me.btnSearch = New System.Windows.Forms.Button()
        Me.txtFile = New System.Windows.Forms.TextBox()
        Me.lblFile = New System.Windows.Forms.Label()
        Me.lblDirectory = New System.Windows.Forms.Label()
        Me.lstFilesFound = New System.Windows.Forms.ListBox()
        Me.cboDirectory = New System.Windows.Forms.ComboBox()
        Me.SuspendLayout()
        ' 
        ' btnSearch 
        ' 
        Me.btnSearch.Location = New System.Drawing.Point(608, 248)
        Me.btnSearch.Name = "btnSearch"
        Me.btnSearch.TabIndex = 0
        Me.btnSearch.Text = "Search"
        AddHandler Me.btnSearch.Click, AddressOf Me.btnSearch_Click
        ' 
        ' txtFile 
        ' 
        Me.txtFile.Location = New System.Drawing.Point(8, 40)
        Me.txtFile.Name = "txtFile"
        Me.txtFile.Size = New System.Drawing.Size(120, 20)
        Me.txtFile.TabIndex = 4
        Me.txtFile.Text = "*.dll"
        ' 
        ' lblFile 
        ' 
        Me.lblFile.Location = New System.Drawing.Point(8, 16)
        Me.lblFile.Name = "lblFile"
        Me.lblFile.Size = New System.Drawing.Size(144, 16)
        Me.lblFile.TabIndex = 5
        Me.lblFile.Text = "Search for files containing:"
        ' 
        ' lblDirectory 
        ' 
        Me.lblDirectory.Location = New System.Drawing.Point(8, 96)
        Me.lblDirectory.Name = "lblDirectory"
        Me.lblDirectory.Size = New System.Drawing.Size(120, 23)
        Me.lblDirectory.TabIndex = 3
        Me.lblDirectory.Text = "Look In:"
        ' 
        ' lstFilesFound 
        ' 
        Me.lstFilesFound.Location = New System.Drawing.Point(152, 8)
        Me.lstFilesFound.Name = "lstFilesFound"
        Me.lstFilesFound.Size = New System.Drawing.Size(528, 225)
        Me.lstFilesFound.TabIndex = 1
        ' 
        ' cboDirectory 
        ' 
        Me.cboDirectory.DropDownWidth = 112
        Me.cboDirectory.Location = New System.Drawing.Point(8, 128)
        Me.cboDirectory.Name = "cboDirectory"
        Me.cboDirectory.Size = New System.Drawing.Size(120, 21)
        Me.cboDirectory.TabIndex = 2
        Me.cboDirectory.Text = "ComboBox1"
        ' 
        ' Form1 
        ' 
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(688, 277)
 
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnSearch, Me.txtFile, Me.lblFile, Me.lblDirectory, Me.lstFilesFound, Me.cboDirectory})
 
        Me.Name = "Form1"
        Me.Text = "Form1"
        AddHandler Me.Load, AddressOf Me.Form1_Load
 
        Me.ResumeLayout(False)
    End Sub
#End Region
 
    ''' <summary> 
    ''' The main entry point for the application 
    ''' </summary> 
    <STAThread()> _
    Private Shared Sub Main()
        Application.Run(New Form1())
    End Sub
 
    Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        lstFilesFound.Items.Clear()
        txtFile.Enabled = False
        cboDirectory.Enabled = False
        btnSearch.Text = "Searching..."
        Me.Cursor = Cursors.WaitCursor
        Application.DoEvents()
        DirSearch(cboDirectory.Text)
        btnSearch.Text = "Search"
        Me.Cursor = Cursors.[Default]
        txtFile.Enabled = True
        cboDirectory.Enabled = True
    End Sub
 
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        cboDirectory.Items.Clear()
        For Each s As String In Directory.GetLogicalDrives()
            cboDirectory.Items.Add(s)
        Next
        cboDirectory.Text = "C:\"
    End Sub
 
    Private Sub DirSearch(ByVal sDir As String)
        Try
            For Each d As String In Directory.GetDirectories(sDir)
                For Each f As String In Directory.GetFiles(d, txtFile.Text)
                    lstFilesFound.Items.Add(f)
                Next
                DirSearch(d)
            Next
        Catch excpt As System.Exception
            Console.WriteLine(excpt.Message)
        End Try
    End Sub
End Class

Open in new window

0
 
LVL 15

Accepted Solution

by:
oobayly earned 250 total points
ID: 24328178
In the method, DirSearch you are searching for files several times in each directory. Try the following.
    Private Sub DirSearch(ByVal sDir As String)
        Try
            For Each f As String In Directory.GetFiles(sDir, txtFile.Text)
               lstFilesFound.Items.Add(f)
            Next
            For Each d As String In Directory.GetDirectories(sDir)
                DirSearch(d)
            Next
        Catch excpt As System.Exception
            Console.WriteLine(excpt.Message)
        End Try
    End Sub

Open in new window

0
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
LVL 1

Author Comment

by:Chris Jones
ID: 24329411
ok this still locks up on me
0
 
LVL 1

Author Comment

by:Chris Jones
ID: 24329472
ok i see my drive is to full so it locks it up

is there a way i can have a label and everytime the file changes it shows in that label?
0
 
LVL 15

Expert Comment

by:oobayly
ID: 24334180
Best bet is to use a BackgroundWorker component.
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

You'd put the code that searches for the files in the DoWork event. For each directory you could call the ReportProgress method, passing the current directory.

From the ProgressChanged event you can update the UI, ie. displaying the current directory in a label.

One thing to note, do not attempt to update the UI from the DoWork event as it will throw an exception. All updates to the UI should be done in the ProgressChanged event.
0
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 250 total points
ID: 24338207
"is there a way i can have a label and everytime the file changes it shows in that label?"

Using oobayly's last code snippet, if you want to make the app "responsive" and update during execution WITHOUT a background worker then you need to insert a call to "Application.DoEvents()" in there:
    Private Sub DirSearch(ByVal sDir As String)
        Try
            For Each f As String In Directory.GetFiles(sDir, txtFile.Text)
               lstFilesFound.Items.Add(f)
 
               Label1.Text = f
               Application.DoEvents()
            Next
            For Each d As String In Directory.GetDirectories(sDir)
                DirSearch(d)
            Next
        Catch excpt As System.Exception
            Console.WriteLine(excpt.Message)
        End Try
    End Sub

Open in new window

0
 
LVL 1

Author Comment

by:Chris Jones
ID: 24338315
wow you guys are awesome i wish i can give more points for the great help you guys have given me
0
 
LVL 1

Author Comment

by:Chris Jones
ID: 24338488
one more thing

i have a text file with filenames is there anyway i can search that textfile from  for the file located in that text file ?

my code is posted above
0
 
LVL 1

Author Comment

by:Chris Jones
ID: 24338775
here is the codee that can read my file but not sure how i can have this post in my search text box and search hall my files in my textfile



MY READ CODE
    Private Sub readfile()
        Dim i As Long
        Dim file As String = "C:\List.txt"
 
        'Read all of the lines of the file into an array
        Dim lines As String() = IO.File.ReadAllLines(file)
        Dim databasePath As String = lines(i)
    End Sub

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 24339194
You are getting strings from the file, one per line.  Got it.
Now what do these strings look like?  Are they actually wildcard strings like "car*.txt", or "*.doc"?
Or are you looking for EXACT filename matches?...
0
 
LVL 1

Author Comment

by:Chris Jones
ID: 24343450
no its names like

car
house
boats
hands
beach
texas
state
etc.......................
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 24344407
Ok...and how does that correlate with your search algorithm?

Are you looking for "car.txt"?..."car20090509.txt"?...etc

0
 
LVL 1

Author Comment

by:Chris Jones
ID: 24344682
yes something like
car20090509.txt but all one file

exmaple explorer.exe will be in my test file
or
rdc.exe
system32.dll
etc......

i should have mad it more understandable earlyer
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 24345076
Ok...cool.  So we are looking for EXACT filename matches.

Now explain to me what you want to do with these filenames with respect to the TEXTBOX.  Are you trying to "pre-load" these values into the textbox and then they get used for the search critieria?

Obviously you are looking for more than one filename...how do you want them DELIMITED?

How about using colon ":"?  (not a valid char for a filename)

    explorer.exe: rdc.exe: system32.dll

Or are you trying to pass just ONE filename at a time to the search and run them separately?
0
 
LVL 1

Author Comment

by:Chris Jones
ID: 24351293
yes i am trying to pass 1 file name at a time and search that folder for each file in my text file
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 24478798
Hey blingtec903....where are you with this question?  I'm cleaning out my Inbox and trying to get back to the old questions in there that are "lost".  Do you still need help?
0
 
LVL 1

Author Comment

by:Chris Jones
ID: 24493677
ok i am done sorry i forgot to close this everythinhg owrks thanks
0
 
LVL 1

Author Closing Comment

by:Chris Jones
ID: 31579012
Thanks for all the help this works great
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Put window Form inside tab page 10 33
C# Single Form 8 42
Ajax Panel Not Updating When Triggered By Timer 4 72
vb.net class 3 11
Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

785 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question