Results 1 to 31 of 31

Thread: [02/03] Searching for a file by name

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    Talking [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

  2. #2
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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:
    1. Dim OpenFileProcess As New Process
    2.         OpenFileProcess.StartInfo.FileName = FileName
    3.         OpenFileProcess.StartInfo.ErrorDialog = True
    4.         OpenFileProcess.Start()
    In life you can be sure of only two things... death and taxes. I'll take death.

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    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

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [02/03] Searching for a file by name

    E.g.
    VB Code:
    1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    2.     Dim path As String = Me.GetFullPath(Application.StartupPath, "MyFile.txt")
    3.  
    4.     If Not path Is Nothing Then
    5.         Process.Start(path)
    6.     End If
    7. End Sub
    8.  
    9. Private Function GetFullPath(ByVal folder As String, ByVal file As String) As String
    10.     Dim path As String = IO.Path.Combine(folder, file)
    11.  
    12.     If Not IO.File.Exists(path) Then
    13.         path = Nothing
    14.  
    15.         For Each subfolder As String In IO.Directory.GetDirectories(folder)
    16.             path = Me.GetFullPath(subfolder, file)
    17.  
    18.             If Not path Is Nothing Then
    19.                 Exit For
    20.             End If
    21.         Next subfolder
    22.     End If
    23.  
    24.     Return path
    25. 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.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    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!?!

  6. #6
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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.
    In life you can be sure of only two things... death and taxes. I'll take death.

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    Re: [02/03] Searching for a file by name

    k thanks

  8. #8
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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:
    1. 'Import the namespace System.IO
    2. Imports System.IO
    3. Public Class Form1
    4.  
    5.     Private FileFound As Boolean = False
    6.  
    7.     Private Sub ButtonSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSearch.Click
    8.         FileFound = False
    9.         FindAndLaunchFile("C:\", TextBoxFindFile.Text)
    10.     End Sub
    11.  
    12.     Private Sub FindAndLaunchFile(ByVal Dir As String, ByVal SearchString As String)
    13.         Dim DirFiles() As String = Directory.GetFiles(Dir)
    14.         Dim TempFileInfo As FileInfo
    15.         For Each TempFile As String In DirFiles
    16.             TempFileInfo = New FileInfo(TempFile)
    17.             If TempFileInfo.Name.ToLower = SearchString.ToLower Then
    18.                 Dim OpenFileProcess As New Process
    19.                 OpenFileProcess.StartInfo.FileName = TempFileInfo.FullName
    20.                 OpenFileProcess.StartInfo.ErrorDialog = True
    21.                 OpenFileProcess.Start()
    22.                 FileFound = True
    23.                 Exit For
    24.             End If
    25.         Next
    26.         If FileFound = False Then
    27.             'Recursivly go through all sub directories
    28.             Dim Directories() As String = Directory.GetDirectories(Dir)
    29.             For Each TempDir As String In Directories
    30.                 FindAndLaunchFile(TempDir, SearchString)
    31.             Next
    32.         End If
    33.     End Sub
    34. End Class

    Hope this helps.
    In life you can be sure of only two things... death and taxes. I'll take death.

  9. #9

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    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

  10. #10
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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:
    1. Imports System.Text.RegularExpressions

    Then change the line where it check for the filename=searchname

    VB Code:
    1. If Regex.Replace(TempFileInfo.Name.ToLower, TempFileInfo.Extension, "") = SearchString.ToLower Then
    2.                 'Add to item to the list view here
    3.  
    4.                 'Replace this next line
    5.                 Console.WriteLine(TempFileInfo.Name)
    6.             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
    In life you can be sure of only two things... death and taxes. I'll take death.

  11. #11

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    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?

  12. #12
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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:
    1. FindAndLaunchFile("C:\", txtSearchText &".doc")
    2. FindAndLaunchFile("C:\", txtSearchText &".xls")

    You would need to rip this part out however:

    VB Code:
    1. Dim OpenFileProcess As New Process
    2.                 OpenFileProcess.StartInfo.FileName = TempFileInfo.FullName
    3.                 OpenFileProcess.StartInfo.ErrorDialog = True
    4.                 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
    In life you can be sure of only two things... death and taxes. I'll take death.

  13. #13
    Addicted Member
    Join Date
    Aug 2002
    Posts
    224

    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

  14. #14
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    Re: [02/03] Searching for a file by name

    Thank you. Glad to hear you liked it.
    In life you can be sure of only two things... death and taxes. I'll take death.

  15. #15

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    Cool 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

  16. #16
    Lively Member SharkC382's Avatar
    Join Date
    Jul 2007
    Location
    Kennesaw, Ga
    Posts
    68

    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

  17. #17

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    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.

  18. #18
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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
    In life you can be sure of only two things... death and taxes. I'll take death.

  19. #19

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    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.

  20. #20

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    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?

  21. #21
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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.
    In life you can be sure of only two things... death and taxes. I'll take death.

  22. #22

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    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.
    Last edited by Quicksilver2002; Jul 10th, 2007 at 11:46 AM.

  23. #23
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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.
    In life you can be sure of only two things... death and taxes. I'll take death.

  24. #24

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    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.

  25. #25
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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.
    In life you can be sure of only two things... death and taxes. I'll take death.

  26. #26

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    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..............

  27. #27
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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
    In life you can be sure of only two things... death and taxes. I'll take death.

  28. #28
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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:
    1. 'When you find a file with the name that matches add it like this
    2.       Dim TempListViewItem As New ListViewItem(TempFileInfo.Name)
    3.       '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
    4.       TempListViewItem.Tag = TempFileInfo.FullName
    In life you can be sure of only two things... death and taxes. I'll take death.

  29. #29
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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.
    In life you can be sure of only two things... death and taxes. I'll take death.

  30. #30

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Posts
    92

    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.

  31. #31
    Fanatic Member cpatzer's Avatar
    Join Date
    Sep 2004
    Posts
    537

    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?
    In life you can be sure of only two things... death and taxes. I'll take death.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width