Saturday, December 8, 2012

Search a file

First in Visual Basic .NET


Search for files in all directories and subdirectories. Find files with a specific pattern with Visual Basic (VB.NET).  Learn to store then in a ListBox or any list.
But first let’s start from a previous post: Windows 8 Search Box with UserControl
We created a UserControl1 with one textbox and one button. The UserControl is use to create a search file or search web site from a custom Windows Start Menu.

TreeView for Windows 8 Start

From the original code, I added 1 member for a new form named Form2. The Form2 will contain a list of results. The search button will call a function findfiles. Here is the code example:



Public Class UserControl1
    Public oForm2 As Form2 = Nothing

    Private Sub UserControl1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        findfiles()
    End Sub





    Private Sub findfiles()

        If oForm2 Is Nothing OrElse oForm2.IsDisposed Then
            oForm2 = New Form2
            oForm2.Show()
        End If

        oForm2.ListBox1.Items.Clear()

        For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
    "c:\temp\", FileIO.SearchOption.SearchAllSubDirectories, "*.dll")


            oForm2.ListBox1.Items.Add(foundFile)

        Next

    End Sub
  

End Class





The code is simple.

First thing, FileSystem.GetFiles will retrieve all the files that respect the entire pattern inside the arguments.  Is important to select SearchAllSubDirectories or you will not have all the results inside your path. Also, the (*) star means that the beginning is not important. It acts like a joker.

The function will list in a new form all the files that end with .dll

Using this example is very simple and has his limitation. So you might have to improve the code to make it more reliable.  Not because the function will skip values, but it may encounter exceptions.


The path is not valid

Invalid characters, path at zero length, white space, path do not exist, path too long. Well you have to check all the things that might cause this type of problem. You have no choice or your code will soon or later crash.  Also be careful with special characters like Chinese, French, Japanese… name them!
Invalid Characters

Security Problem

Permission, authorization, shortcut to restricted folder will cause you problem. Try at least to avoid those directories or files. There is no magic; you have to skip them because the FileSystem.GetFiles can’t handle exceptions.

System Recovery

Folder shortcut

Stay alert when you access into My Documents. Even if you are using the Environment.SpecialFolder values, your program must be careful when it reach “shortcut directories”.  In the next tables, I gave 3 example of false information returned from you GetDirectories. There are not a lot of them in your computer and is easier the simply avoid them. It is always the same pattern.

False directories
Real directories
C:\Users\checkkay\My Pictures
C:\Users\checkkay\My Music
C:\Users\checkkay\My Videos

C:\Users\checkkay\Pictures
C:\Users\checkkay\Music
C:\Users\checkkay\Videos


Folder shortcut


So looking for a file in your computer is not complicate. It is just that you have to think at all possibilities. The FileSystem.GetFiles is simply not smart enough. So here is a code example a little bit better than the first one:


    Private Sub findfiles()

        Dim dirPath As String
        Dim path_valid As Boolean
        path_valid = True

        dirPath = "c:\temp\" ' temp = no access problem
        dirPath = "c:\System Recovery" ' System Recovery = access problem




        '----------------------------------------------
        ' CHECK PATH IF VALID
        '----------------------------------------------
        'trim the sPath to remove space before and after the String
        dirPath = Trim(dirPath)

        'check if sPath is not zero length
        If Len(dirPath) > 0 Then

        Else
            path_valid = False
        End If

        'check for invalid char
        ' \ * | : ? < > / except the \ because is a directory seperator
        ' and * that means to ignore whatever inside the other chars. (optional)
        If InStr(dirPath, "|", CompareMethod.Binary) > 0 Then
            path_valid = False
        End If
        If InStr(dirPath, ">", CompareMethod.Binary) > 0 Then
            path_valid = False
        End If
        If InStr(dirPath, "<", CompareMethod.Binary) > 0 Then
            path_valid = False
        End If
        If InStr(dirPath, "?", CompareMethod.Binary) > 0 Then
            path_valid = False
        End If
        If InStr(dirPath, ":", CompareMethod.Binary) = 2 Then
            'very basic way to check if there is a ":" in the Path.
            Dim str_temp As String = dirPath.Substring(2, Len(dirPath) - 2)
            If InStr(str_temp, ":", CompareMethod.Binary) > 0 Then
                path_valid = False
            End If

        End If
        If InStr(dirPath, "*", CompareMethod.Binary) > 0 Then
            path_valid = False
        End If
        'be careful with non-english caracters


        '----------------------------------------------
        ' SECURITY
        '----------------------------------------------
        Dim oDirectorySecurity As System.Security.AccessControl.DirectorySecurity
        Dim oAuthorizationRuleCollection As System.Security.AccessControl.AuthorizationRuleCollection
        Dim oRule As System.Security.AccessControl.FileSystemAccessRule
        Dim Security_valid As Boolean

        Security_valid = False
        oDirectorySecurity = IO.Directory.GetAccessControl(dirPath)
        oAuthorizationRuleCollection = oDirectorySecurity.GetAccessRules(True, True, Type.GetType("System.Security.Principal.NTAccount"))

        For Each oRule In oAuthorizationRuleCollection

            If oRule.FileSystemRights = Security.AccessControl.FileSystemRights.FullControl Then
                If InStr(oRule.IdentityReference.Value, My.User.Name) > 0 Then
                    Security_valid = True
                End If
            End If

        Next

        '----------------------------------------------
        ' SECURITY
        '----------------------------------------------
        Dim Is_Folder_shortcut As Boolean
        Is_Folder_shortcut = False
        If dirPath.StartsWith("c:\Users", True, System.Globalization.CultureInfo.CurrentCulture) Then
            'very basic way to force you to be very carefull with that folder
            Is_Folder_shortcut = True
        End If

        '----------------------------------------------
        ' IF ALL OK, THEN DISPLAY THE RESULT
        '----------------------------------------------
        If oForm2 Is Nothing OrElse oForm2.IsDisposed Then
            oForm2 = New Form2
            oForm2.Show()
        End If
        oForm2.ListBox1.Items.Clear()
        If path_valid = True And Security_valid = True And Is_Folder_shortcut = False Then

            For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
                    dirPath, FileIO.SearchOption.SearchAllSubDirectories, "*.dll")

                oForm2.ListBox1.Items.Add(foundFile)

            Next
        Else
            MsgBox("path_valid =" & path_valid & vbCrLf & "Security_valid =" & Security_valid)
        End If

    End Sub



Again, this is very basic, but I hope you see the difficulties in searching files in your computer. There a other things you have to preoccupy. But I don’t want to make a post too long.

Here are some references I google:



Good to read:

My other related post: Create the Search TextBox
My other related post: Create your Windows 8 Start Menu
Visit my Official Web Site : Check Technologies

No comments:

Post a Comment