Solved

Find file

Posted on 2011-09-27
8
549 Views
Last Modified: 2012-08-13
Hi,
How can I find path to some file from my code?
0
Comment
Question by:mastiSoft
8 Comments
 
LVL 8

Expert Comment

by:jawa29
Comment Utility
Hi

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

Jawa29
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
Do you want to isolate the path from a fullname, or do you want to search for the file on the computer?
0
 
LVL 1

Author Comment

by:mastiSoft
Comment Utility
Hi,
I only have a name of the file let say : myprogram.exe .
I have to get path to this file.
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
Do you at least know on which drive it is?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 1

Author Comment

by:mastiSoft
Comment Utility
Yes it have to be in the same dir  where OS are. It use to be C but you never know.
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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
 
LVL 29

Accepted Solution

by:
nffvrxqgrcfqvvc earned 500 total points
Comment Utility
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
 
LVL 1

Author Closing Comment

by:mastiSoft
Comment Utility
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

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

772 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now