Find file

Posted on 2011-09-27
Medium Priority
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.
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

There is an easy way, in .NET, to centralize the treatment of all unexpected errors. First of all, instead of launching the application directly in a Form, you need first to write a Sub called Main, in a module. Then, set the Startup Object to th…
This article will show, step by step, how to integrate R code into a R Sweave document
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
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.
Suggested Courses

765 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