mastiSoft
asked on
Find file
Hi,
How can I find path to some file from my code?
How can I find path to some file from my code?
Do you want to isolate the path from a fullname, or do you want to search for the file on the computer?
ASKER
Hi,
I only have a name of the file let say : myprogram.exe .
I have to get path to this file.
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?
ASKER
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:
n on most systems.
So you must do by performing the search yourself, which might take a long time on a big hard disk
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.
Directory.GetFiles("C:\", "myprogram.exe", SearchOption.AllDirectories)
Unfortunately, with todays security, it almost always bomb with an UnauthorizedAccessExceptioSo 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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.
If this is a VB.NET question then this might help.
http://vbdotnetforum.com/index.php?/topic/1821-get-file-path/
Jawa29