In several situations it is useful to know where your program is running from, one example of this is loading a file that is stored in the application folder (or a sub-folder).

There is an object provided in VB called App, which provides several pieces of useful information about your application, including where it is running from. To see this you need to look at the Path property, eg:
VB Code:
  1. MsgBox App.Path
This will show a message with text something like the following (obviously containing the appropriate path): C:\Program Files\MyApp

You can add this value to a variable to use in a variety of ways (such as specifying a folder to load a file from). For example, if you have a folder called "Pictures" within your application folder, and you wanted to load a picture from that folder, you could use code like this to get the path to the file:
VB Code:
  1. Dim sPicturePath as String
  2. sPicturePath = App.Path & "\Pictures\MyPicture.jpg"
The variable sPicturePath will now contain something like: C:\Program Files\MyApp\Pictures\MyPicture.jpg, and can be used in place of the file name.

Important note: There is a quirk with the way that App.Path works when your application is in the root folder of a drive (eg: in c:\ rather than c:\my folder\); In this situation it will return the path with a \ at the end, whereas normally it doesn't. If you add an extra \ (as in the above example) you will get errors.

To get around this issue you need to only add the \ if it is needed, you can do this using an If statement, or use a function to return it for you. Here is an example function you can use:
VB Code:
  1. Function App_Path() As String
  2. 'Returns the current App.Path with a \ on the end
  4.   If Right(App.Path, 1) = "\" Then
  5.     App_Path = App.Path
  6.   Else
  7.     App_Path = App.Path & "\"
  8.   End If
  10. End Function
If you want to use this, simply paste it into the "General Declarations" section at the top of a Form or Module.