-
[02/03] Searching for a file by name
Hey everyone....I'm looking to start a new project, but am having a problem getting started!
I want to build a program that I can type the "name" of a file into a text box hit enter and it will open that file up with the right Program.
For Example. If I have a CAD drawing named Test.dwg, I want to type Test into the textbox hit enter and have that drawing open in CAD.
All my drawings are in one location (F:/CAD) but from there they are split into many different subdirectories (F:/CAD/25T) or (F:/CAD/25U)
Does anyone know where i can find something to point me in the right direction?
Thanks
-
Re: [02/03] Searching for a file by name
Quicksilver,
What you are trying to do should be fairly easy. You need to use the Directory object in System.IO namespace to search recursively through directories and subdirectories where the files are stored.
From there you can just start a new process. The OS will do the rest.
VB Code:
Dim OpenFileProcess As New Process
OpenFileProcess.StartInfo.FileName = FileName
OpenFileProcess.StartInfo.ErrorDialog = True
OpenFileProcess.Start()
-
Re: [02/03] Searching for a file by name
Thanks for the reply...I'm fairly new to VB so I don't know what you mean by "You need to use the Directory object in System.IO namespace to search recursively through directories and subdirectories where the files are stored"
Do u know where i can find a sample of this if it's in VB6 thats ok too.
Thanks
-
Re: [02/03] Searching for a file by name
E.g.
VB Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim path As String = Me.GetFullPath(Application.StartupPath, "MyFile.txt")
If Not path Is Nothing Then
Process.Start(path)
End If
End Sub
Private Function GetFullPath(ByVal folder As String, ByVal file As String) As String
Dim path As String = IO.Path.Combine(folder, file)
If Not IO.File.Exists(path) Then
path = Nothing
For Each subfolder As String In IO.Directory.GetDirectories(folder)
path = Me.GetFullPath(subfolder, file)
If Not path Is Nothing Then
Exit For
End If
Next subfolder
End If
Return path
End Function
Just note that if the same file name exists in two folders the second will never be reached using this method. You'd have to adjust it to search the entire folder tree regardless and return all paths to files with the specified name.
-
Re: [02/03] Searching for a file by name
Thanks for your reply! So if i understand this right...would I replace "MyFile.txt" with the path to the application that i want to run, Replace Folder with the path to the directories (C:\Cad\), and file would be what the search text box is. Is that right!?!
-
Re: [02/03] Searching for a file by name
Give me a minute or so and I will post code that will complete the trick for you.
-
Re: [02/03] Searching for a file by name
-
Re: [02/03] Searching for a file by name
This example will search recursively through base folder given. This example assumes that you have a TextBox named "TextBoxFindFile" and a Button named "ButtonSearch".
VB Code:
'Import the namespace System.IO
Imports System.IO
Public Class Form1
Private FileFound As Boolean = False
Private Sub ButtonSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSearch.Click
FileFound = False
FindAndLaunchFile("C:\", TextBoxFindFile.Text)
End Sub
Private Sub FindAndLaunchFile(ByVal Dir As String, ByVal SearchString As String)
Dim DirFiles() As String = Directory.GetFiles(Dir)
Dim TempFileInfo As FileInfo
For Each TempFile As String In DirFiles
TempFileInfo = New FileInfo(TempFile)
If TempFileInfo.Name.ToLower = SearchString.ToLower Then
Dim OpenFileProcess As New Process
OpenFileProcess.StartInfo.FileName = TempFileInfo.FullName
OpenFileProcess.StartInfo.ErrorDialog = True
OpenFileProcess.Start()
FileFound = True
Exit For
End If
Next
If FileFound = False Then
'Recursivly go through all sub directories
Dim Directories() As String = Directory.GetDirectories(Dir)
For Each TempDir As String In Directories
FindAndLaunchFile(TempDir, SearchString)
Next
End If
End Sub
End Class
Hope this helps.
-
Re: [02/03] Searching for a file by name
Cpatzer You the Man! I've been looking all over trying to figure this out! Thanks alot! My only question to you now is In this Directory I'll be searching is there might be a file named just for example Text.doc and Test.xls right now I have
Private Sub ButtonSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSearch.Click
FileFound = False
FindAndLaunchFile("C:\", txtSearchText &".doc")
End Sub
Is there a easy way to do this: If their are to files like above pop up a form with those to files showing and then you select which one you want to open .doc or .xls
-
Re: [02/03] Searching for a file by name
You could use a ListView control. The Microsoft docs have some really good examples in them for this control.
If you want to check for the file without an extension you will need to import this namespace as well:
VB Code:
Imports System.Text.RegularExpressions
Then change the line where it check for the filename=searchname
VB Code:
If Regex.Replace(TempFileInfo.Name.ToLower, TempFileInfo.Extension, "") = SearchString.ToLower Then
'Add to item to the list view here
'Replace this next line
Console.WriteLine(TempFileInfo.Name)
End If
You will also have to change the loop logic. Right now if it finds a match it will stop searching. Obviously if you want to find multiple matches you will need to let it run it's course.
Now, if you are going to do that and the directory tree is fairly large, you will probably want to run the search in another thread. If you are using VS2005 you can use the BackgroundWorker control. There should be plenty examples of this on the web
and in the help files.
The new thread will allow your main form to still respond while the search is taking place.
--Cheers
-
Re: [02/03] Searching for a file by name
If i want to only check for 2 file extensions for example .doc and .xls would i still need to add the code above?
-
Re: [02/03] Searching for a file by name
No, you could then just keep the code in the original post and call the search like this:
VB Code:
FindAndLaunchFile("C:\", txtSearchText &".doc")
FindAndLaunchFile("C:\", txtSearchText &".xls")
You would need to rip this part out however:
VB Code:
Dim OpenFileProcess As New Process
OpenFileProcess.StartInfo.FileName = TempFileInfo.FullName
OpenFileProcess.StartInfo.ErrorDialog = True
OpenFileProcess.Start()
And replace it with code that would add it to a ListView.
Don't forget to rate my posts if you found them helpful.
--Christian
-
Re: [02/03] Searching for a file by name
Hi,
To Cpatzer
I copy your code and tried it, it's excellent.
Have a nice day
-
Re: [02/03] Searching for a file by name
Thank you. Glad to hear you liked it.
-
Re: [02/03] Searching for a file by name
cpatzer, Its been awhile! Hoping you can still help me out. I've been using this little program awhile now, but have came to a point where I need to change it. I know we talked about it, but If I do a search lets say for "Doc1" and there is a Doc1.doc & doc1.xls I would like to have these files added to a list veiw control. so the user can select which one he wants to open.
I've been playing with it but can't seem to get it to work. Here is what I have as of now. Thanks in advance.
Code:
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
Inherits System.Windows.Forms.Form
Private FileFound As Boolean = False
Dim Num As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Shows Form in Bottom Right corner
Me.SetBounds(Screen.GetWorkingArea(Me).Width - Me.Width, Screen.GetWorkingArea(Me).Height - Me.Height, Me.Width, Me.Height)
Dim PathReader As IO.StreamReader
PathReader = IO.File.OpenText("C:\ISOExplorerPath.ini")
varPath = PathReader.ReadLine()
PathReader.Close()
End Sub
Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Close()
End Sub
Private Sub FindAndLaunchFile(ByVal Dir As String, ByVal SearchString As String)
Dim DirFiles() As String = Directory.GetFiles(Dir)
Dim TempFileInfo As FileInfo
For Each TempFile As String In DirFiles
TempFileInfo = New FileInfo(TempFile)
If TempFileInfo.Name.ToLower = SearchString.ToLower Then
Dim OpenFileProcess As New Process
'OpenFileProcess.StartInfo.FileName = TempFileInfo.FullName
'OpenFileProcess.StartInfo.ErrorDialog = True
'OpenFileProcess.Start()
FileFound = True
Exit For
End If
If Regex.Replace(TempFileInfo.Name.ToLower, TempFileInfo.Extension, "") = SearchString.ToLower Then
'Add to item to the list view here
ListView1.Items.Add(TempFileInfo.Name)
'Replace this next line
Console.WriteLine(TempFileInfo.Name)
End If
Next
If FileFound = False Then
'Recursivly go through all sub directories
Dim Directories() As String = Directory.GetDirectories(Dir)
For Each TempDir As String In Directories
FindAndLaunchFile(TempDir, SearchString)
Next
End If
End Sub
Private Sub MenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim NewPath As New Path
NewPath.ShowDialog()
End Sub
Private Sub txtSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearch.Click
Me.Label2.Text = ""
End Sub
Private Sub txtSearch_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSearch.KeyDown
'If enter key is hit perfoms click on botton "BottonSearch"
If e.KeyCode = Keys.Enter Then
FileFound = False
FindAndLaunchFile(varPath, txtSearch.Text & ".doc")
FindAndLaunchFile(varPath, txtSearch.Text & ".xls")
FindAndLaunchFile(varPath, txtSearch.Text & ".htm")
FindAndLaunchFile(varPath, txtSearch.Text & ".mpp")
If FileFound = False Then
Me.Label2.Text = " File Not Found. Please try again."
End If
End If
End Sub
Private Sub txtSearch_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSearch.KeyPress
'Makes everything typed into textbox uppercase
If Char.IsLower(e.KeyChar) Then
e.KeyChar = Char.ToUpper(e.KeyChar)
End If
End Sub
Private Sub txtSearch_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
Me.Label2.Text = ""
End Sub
End Class
-
Re: [02/03] Searching for a file by name
Thought I'd add in a little something I usually do if I have to use files that can be in other directories or drives, or even on network drives...
I use either an ini-type file or My.Settings and create an array of strings called EnvPaths.
I can then setup any paths I want to check for the file(s) I want to open, and append those paths to a filename, with or without an extension, and my progs look there first.
Quicker than trying to search multiple directories if you know where the files might be.
Regards,
Matt
-
Re: [02/03] Searching for a file by name
Thanks for your reply! I think this might be what your talking about....I do have a ini file that contains the path to the directory i want to search. In this case it contains a path to ther server were all the ISO files are located. Within this directory all files will be either htm, xls, or doc's.
-
Re: [02/03] Searching for a file by name
Quicksilver,
What exactly is the problem/part that isn't working?
It appears at first glance that you are adding the results correctly to the ListView.
If you want the user however to be able to double click on the item to open it you will need to add the full path to the file in question.
I havn't been in the VB world for almost over a year so this might be a little rusty without loading it in the IDE.
Code:
'When you find a file with the name that matches add it like this
Dim TempListViewItem As New ListViewItem(TempFileInfo.Name)
'This adds the full path to the file to the listviewitem's tag attribute so that we can access it when they double click it later
TempListViewItem.Tag = TempFileInfo.FullName
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
'This assumes that you have your listview control set up so that users CANNOT select multiple items
If ListView1.SelectedItems.Count > 0 Then
Dim FileLocation As String = CType(ListView1.SelectedItems.Item(0).Tag, String)
'Do the process start thing here
End If
End Sub
-
Re: [02/03] Searching for a file by name
When i search for a known file. and hit enter. I'll i get is a "Ding" sound and nothing happens. If i enter one that is a known not to be good it errors out like it should.
-
Re: [02/03] Searching for a file by name
one thing i noticed is i don't really have anything in the txtSearch_KeyDown which is used like a 'Click' and is the only way of initiating the search. Any ideas on what should be here?
-
Re: [02/03] Searching for a file by name
So you have a text field and a button correct?
If you want both to work when you click the search button or hit the enter key you will need to set the button as your form's Accept button. This can be done by selecting the form in the IDE and then browsing the forms properties until you find the Accept Button and update it to reflect the name of your search button. So if you had a button named btnSearch you would set your form's accept button to btnSearch.
-
Re: [02/03] Searching for a file by name
No there is no Button the user just hits enter. But from all the changes I made theres nuthing really there anymore.
-
Re: [02/03] Searching for a file by name
Well you definetly don't want to use the keyup or keydown events without interrogating the key pressed as that would start the search with every key stroke. You could use the keydown event and just interogate the key pressed to see if it is the enter key. I think the property is e.Key or something like that in the keydown event.
So basically you just need to add the event handler for the keydown event on the text box, if they hit the enter key then you start the search with the text that is in the TextBox control.
-
Re: [02/03] Searching for a file by name
Yes that is all in the current code. That part of everthing thing works. Just cant get the files to show in the list view.
-
Re: [02/03] Searching for a file by name
Why don't you start a new project with just a ListView control on the form. Then in the form load event try adding items. There is quite a bit of good examples in the help files on how to do this. By isolating the problem you will have a better chance of figuring out what is going wrong.
Hope this helps.
-
Re: [02/03] Searching for a file by name
What variable does the file names get loaded into?
I've tried
ListView1.Items.Add(TempFileInfo.name) "I get a underline under TempFileInfo
I don't knwo what to put in there..............
-
Re: [02/03] Searching for a file by name
Not sure exactly the code you are using but that should be correct. Only you need to capitalize the Name portion.
So, ListView1.Items.Add(TempFileInfo.Name)
This would be the name of the file without the path so
C:\home\bla.txt would come out as bla.txt then the property TempFileInfo.FullName would contain the full path to the file C:\home\bla.txt
-
Re: [02/03] Searching for a file by name
Also, if you use the code I supplied above to add your listviewitems you will be able to launch the file without adding the full path to the file in the viewable portion of the listview.
vb Code:
'When you find a file with the name that matches add it like this
Dim TempListViewItem As New ListViewItem(TempFileInfo.Name)
'This adds the full path to the file to the listviewitem's tag attribute so that we can access it when they double click it later
TempListViewItem.Tag = TempFileInfo.FullName
-
Re: [02/03] Searching for a file by name
If you get really stuck. Start a new project, start with the code I gave you the first time, and work from that. Then, once you have the problem isolated you can change your existing project so that it works correctly.
-
Re: [02/03] Searching for a file by name
Ok Ill be taking your advice and starting New Project.
One more question before I do though.......
This code you had originally gave me was like this:
Code:
Private Sub FindAndLaunchFile(ByVal Dir As String, ByVal SearchString As String)
Dim DirFiles() As String = Directory.GetFiles(Dir)
But i moved this all so that when the user hits enter this will occur. Now it looks like this:
Code:
Private Sub txtSearch_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSearch.KeyDown
If e.KeyCode = Keys.Enter Then
Dim DirFiles() As String = Directory.GetFiles(Dir)
When I hit enter i get a a error saying 'Dir' function must first be called with a 'PathName' argument.
So then I notice the code you sent has the code ByVal Dir As String so i tryed adding that to the other section and i get a error saying saying
'Cannot handle event Public event Key Down because they do not have the same signature.' with this underlined
Code:
Handles txtSearch.KeyDown
I know your pry sick of me, but i had to ask before i re-invent the wheel tonight.
-
Re: [02/03] Searching for a file by name
Right, an objects event has to match the signature of the event the author, in this case MS, wrote. This means don't add it as an argument to the keydown event.
So all you have to do is define the variable Dir (as a string) directory path i.e. "c:\" or "h:\mystuff\" that way the directory object knows what directory to look in. Make sense?