0

How to get file path within VB class - assuming our VB class in located in code behind file of ASP.net webpage?

e.g. We are viewing ASP.net webpage ( http://localhost:1253/website/web-page.aspx ) - and our VB class in located in web-page.aspx.vb file.

Public Class FileLocation

    Public Function GetFileLocation() As String

        Dim location as string = '
        // get "c:/intenpub/website/file.jpg" when only filename "file.jpg" is known 
        Return location

    End Function

End Class
Iladarsda
  • 10,640
  • 39
  • 106
  • 170
  • So you're asking for a recursive file search? – Douglas Barbin Nov 13 '13 at 14:46
  • 1
    It's not clear what you mean. If only the name of the file is known, how are you expecting to get the path? Are you searching the whole file system? – David Nov 13 '13 at 14:47
  • 1
    What if there are 20 different `file.jpg`s scattered around the hard disk? This should return `IEnumerable(Of String)` not `String` as there are many potential matches – Basic Nov 13 '13 at 14:47
  • 1
    possible duplicate of [Recursive File Search in .net](http://stackoverflow.com/questions/437728/recursive-file-search-in-net) – J... Nov 13 '13 at 14:52
  • This VB class is within `index.aspx.vb` file which is located at `c:/intnedpub/website/index.aspx.vb` – Iladarsda Nov 13 '13 at 14:52
  • 1
    What file are you trying to locate? Are you trying to locate your VB file? Your VB file does not exist when it is being run; it is compiled into a new program and the program is run. Are you trying to find a file with a particular name? Then you cannot guarantee that a file with the name you are looking for exists. You cannot guarantee that only one file with that name exists. To perform that search you would need to recursively scan the contents of every directory on the PC, and for every file in the directory check if it has the same name, and for every directory, perform the function again. – Frosty840 Nov 13 '13 at 15:09

2 Answers2

0

anYou can get the location of a known file, say if you know that "file.jpg" is in the website's root...

My.Application.Info.DirectoryPath 
'Returns the directory path of an application - there are ones for web stuff too

and you can check to see if a file exists in a specific known location...

If System.IO.File.Exists(My.Application.Info.DirectoryPath + "\file.jpg") Then
'Do Something
End If

But you can't just easily get a location of a file named "whatever" without searching the entire directory, which may include several results and you wouldn't know which is the correct one....

Barry Franklin
  • 1,781
  • 1
  • 27
  • 45
0

If you are trying to find a file by name in a specific directory or a directory and its subdirectories, you can use a built in .NET function:

Imports System.IO

Directory.GetFiles("c:/intenpub/website/", "file.jpg", SearchOption.TopDirectoryOnly)
Directory.GetFiles("c:/intenpub/website/", "file.jpg", SearchOption.AllDirectories)
djv
  • 15,168
  • 7
  • 48
  • 72