Chris Jones
asked on
Recursive File Searching In VB.NET
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
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
ASKER
hello
i have converted and tested the code but it is locking up on my system
HERE IS THE CODE
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ok this still locks up on me
ASKER
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?
is there a way i can have a label and everytime the file changes it shows in that label?
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.
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.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
wow you guys are awesome i wish i can give more points for the great help you guys have given me
ASKER
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
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
ASKER
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
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
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?...
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?...
ASKER
no its names like
car
house
boats
hands
beach
texas
state
etc.......................
car
house
boats
hands
beach
texas
state
etc.......................
Ok...and how does that correlate with your search algorithm?
Are you looking for "car.txt"?..."car20090509. txt"?...et c
Are you looking for "car.txt"?..."car20090509.
ASKER
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
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
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?
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?
ASKER
yes i am trying to pass 1 file name at a time and search that folder for each file in my text file
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?
ASKER
ok i am done sorry i forgot to close this everythinhg owrks thanks
ASKER
Thanks for all the help this works great
http://support.microsoft.com/kb/303974