Find file

Posted on 2011-09-27
Last Modified: 2012-08-13
How can I find path to some file from my code?
Question by:mastiSoft
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Expert Comment

ID: 36710572

If this is a VB.NET question then this might help.

LVL 40
ID: 36710965
Do you want to isolate the path from a fullname, or do you want to search for the file on the computer?

Author Comment

ID: 36714582
I only have a name of the file let say : myprogram.exe .
I have to get path to this file.
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

LVL 40
ID: 36715032
Do you at least know on which drive it is?

Author Comment

ID: 36719347
Yes it have to be in the same dir  where OS are. It use to be C but you never know.
LVL 40
ID: 36719793
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()
         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

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.

LVL 29

Accepted Solution

nffvrxqgrcfqvvc earned 500 total points
ID: 36719887
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
            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("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
            Return _rootPath
        End Get
    End Property
    Public ReadOnly Property FileName As String
            Return _fileName
        End Get
    End Property
End Class

Open in new window


Author Closing Comment

ID: 36817550
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.

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question