Link to home
Start Free TrialLog in
Avatar of mastiSoft
mastiSoft

asked on

Find file

Hi,
How can I find path to some file from my code?
Avatar of jawa29
jawa29
Flag of United Kingdom of Great Britain and Northern Ireland image

Hi

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

Jawa29
Do you want to isolate the path from a fullname, or do you want to search for the file on the computer?
Avatar of mastiSoft
mastiSoft

ASKER

Hi,
I only have a name of the file let say : myprogram.exe .
I have to get path to this file.
Do you at least know on which drive it is?
Yes it have to be in the same dir  where OS are. It use to be C but you never know.
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.


ASKER CERTIFIED SOLUTION
Avatar of nffvrxqgrcfqvvc
nffvrxqgrcfqvvc

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.