Find the Location of your Exe
and the Windows Folders

This sample presents solutions to a few very common questions:

  1. Where are the Windows folders?
  2. Where does my executable reside?
  3. What is the 8 character short path equivalent of a given path?

Determine Location of Executable, Windows folders and the equivalent short path names
Download Source Code

Path to the Windows and the System Folders

Often you need to know the paths to the Windows and the System folders.   If your application is to run on multiple platforms you can't assume C:\Windows or C:\Winnt. You need to determine these paths dynamically. Windows provides the GetWindowsDirectory function to return the location of the Windows folder and the GetSystemDirectory function to return the System folder.

Here are sample calls to these functions:

    Dim sBuffer As String
    sBuffer = Space$(MAX_PATH)
    lblDir(0) = GetWindowsDirectory(sBuffer, MAX_PATH)
    lblDir(0) = Left$(sBuffer, Len(sBuffer) - 1)

    sBuffer = Space$(MAX_PATH)
    lblDir(1) = GetSystemDirectory(sBuffer, MAX_PATH)
    lblDir(1) = Left$(sBuffer, Len(sBuffer) - 1)

Locating Your Executable

Sometimes your application may need to know the folder its executable resides in so it can find other folders based on a relative path. The obvious solution is to use the .Path property of the App object (App.Path). However, you may be in for a surprise when you see the results when your executable resides on a server in a network directory. App.Path often returns erroneous results like returning the path to the system folder instead.

You can use the GetModuleFileName and GetModuleHandle functions instead to display the proper information.

    Dim sBuffer As String

    sBuffer = Space$(MAX_PATH)
    lHandle = GetModuleHandle(App.EXEName)
    lResult = GetModuleFileName(lHandle, sBuffer, MAX_PATH)
    lblPath = sBuffer

When you run the sample program, it will return the path where you have Visual Basic installed since that is the executable currently running the code. Once you compile the program and run it you will see the correct results.

Short Path Name

It is nice to use long, descriptive folder names. However, many times the equivalent short path name is required. For example, to start your application automatically with Windows you can add your executable's path to the HKey_Local_Machine\Software\Microsoft\Windows\CurrentVersion\Run registry key provided you use the short path. This code shows you how to do it with the GetShortPathName API function.

Instructions

Download the source code and compile it to an executable.   Copy the .exe to a network folder if possible. Run the program to display the folder in which the executable resides as well as the Windows and System folders.




About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page