Find file

Hi,
How can I find path to some file from my code?
LVL 1
mastiSoftAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
nffvrxqgrcfqvvcConnect With a Mentor Commented:
Looking for a specific file is trivial at best since the same file name could be located on the same volume in different directories. That means when you search for the file you can have multiple entries but in different sub-directories on the same volume. The following example will return the first match found so if you know this file name is something unique then it would work. You can also find which location the System directory is located and strip to the root this would give you the volume windows has been installed.

Add BackgroundWorker Control
Add Button

Imports System.Text
Imports System.IO

Public Class Form1

    Private Declare Unicode Function SearchTreeForFileW Lib "dbghelp.dll" (ByVal RootPath As String, ByVal InputPathName As String, ByVal OutputPathBuffer As StringBuilder) As Boolean

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

        Dim fileArgs As New FindFileArgs(Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)), "calc.exe")

        If Not BackgroundWorker1.IsBusy Then
            BackgroundWorker1.RunWorkerAsync(fileArgs)
        Else
            Debug.Print("Search in progress. please wait...")
        End If
    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Dim buffer As New StringBuilder(65536)
        Dim ffa As FindFileArgs = DirectCast(e.Argument, FindFileArgs)
        SearchTreeForFileW(ffa.RootPath, ffa.FileName, buffer)
        e.Result = buffer.ToString
    End Sub
     
    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        If e.Result.ToString.Length <> 0 Then
            MsgBox(e.Result.ToString)
        Else
            MsgBox("Not Found")
        End If
    End Sub

End Class

Public NotInheritable Class FindFileArgs
    Private _rootPath As String = String.Empty
    Private _fileName As String = String.Empty
    Public Sub New(ByVal rootPath As String, ByVal fileName As String)
        _rootPath = rootPath
        _fileName = fileName
    End Sub
    Public ReadOnly Property RootPath As String
        Get
            Return _rootPath
        End Get
    End Property
    Public ReadOnly Property FileName As String
        Get
            Return _fileName
        End Get
    End Property
End Class

Open in new window

0
 
jawa29Commented:
Hi

If this is a VB.NET question then this might help.
http://vbdotnetforum.com/index.php?/topic/1821-get-file-path/

Jawa29
0
 
Jacques Bourgeois (James Burger)PresidentCommented:
Do you want to isolate the path from a fullname, or do you want to search for the file on the computer?
0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
mastiSoftAuthor Commented:
Hi,
I only have a name of the file let say : myprogram.exe .
I have to get path to this file.
0
 
Jacques Bourgeois (James Burger)PresidentCommented:
Do you at least know on which drive it is?
0
 
mastiSoftAuthor Commented:
Yes it have to be in the same dir  where OS are. It use to be C but you never know.
0
 
Jacques Bourgeois (James Burger)PresidentCommented:
There is a nice command to do that in the framework:
Directory.GetFiles("C:\", "myprogram.exe", SearchOption.AllDirectories)

Open in new window

Unfortunately, with todays security, it almost always bomb with an UnauthorizedAccessException on most systems.

So you must do by performing the search yourself, which might take a long time on a big hard disk

Imports System.IO

Module Module1

Public Sub Main()

   MessageBox.Show(CheckDirectory("C:\", "myprogram.exe"))

End Sub

Public Function CheckDirectory(searchStart As String, fileToFind As String) As String

   Dim currentFolder As DirectoryInfo = New DirectoryInfo(searchStart)
   Dim result As String

   If currentFolder.GetFiles(fileToFind).Count > 0 Then
      Return searchStart
   End If

   For Each folder As DirectoryInfo In currentFolder.GetDirectories()
      Try
         result = CheckDirectory(folder.FullName, fileToFind)
         If result IsNot Nothing Then Return result
      Catch ex As UnauthorizedAccessException
         'Do nothing. Skip to the next accessible directory.
      End Try
   Next

End Function

End Module

Open in new window


As presented, it will return the first file of the specified name that it finds. If you want to find all the files of that name, you will have to accumulate then in an array before returning them to the caller.


0
 
mastiSoftAuthor Commented:
Thanks, It was easy to follow. But.. if the file exist in the directory then  it works fast and nice , but if it's not then it takes a lot of time and feels like the program hangs.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.