Search code examples
vb.netinstallationsavesettingfilepath

Setting Correct Filepath for a txt Save - vb.NET


Okay. I feel like this should be programming 101, but I cannot seem to find a decent answer on how to set a file path name to be dynamic enough to be set explicitly to where the exe is installed.

Basically, this application is actually going to be installed in the Users personal folders, probably something like Local Data, and I need to get a txt file that is created by the program to be created into the same directory as the executable.

Current Path:

Dim strFilePath As String = "D:\Development\Bobby\Prototyping\Replication Desktop Client\Replication_Desktop_Client\ClientAccessList.txt"

I want to set it to something like

Dim strCurrentLocationOfEXE As String = HardDriveLetter & Users & CurrentUserPath & InstalledDirectory
Dim strFilePath As String = strCurrentLocationOfEXE & "\ClientAccessList.txt"`

but I can not for the life of me figure out how to get it to determine that, since it is not going to always be installed to the same folder (i.e. Username and perhaps hard drive letter will be different).

Ideas?


Solution

  • You can get the path where the assembly is running with

    Dim fullPath = System.Reflection.Assembly.GetExecutingAssembly().Location
    Dim folderName = Path.GetDirectoryName( fullPath )
    Dim strFilePath = Path.Combine(folderName, "ClientAccessList.txt")
    

    if you want to refer to the current user personal folder for this application then the way to go is through the Environment.SpecialFolder enumaration.
    This enum is independent from the underlying OS (XP, Win7, x64, x32 etc) In this case you could use:

    Dim fullPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
    Dim strFilePath = Path.Combine(fullPath, "your_app_reserved_folder", "ClientAccessList.txt")
    

    In this example "your_app_reserved_folder" should be a folder created during installation of your application where you put per user data files. (Usually this is the recommended way to go to store data files that should be kept separated by user)

    If you want to check the existence of the folder before trying to use it just encapsulate the logic to get the file name in a method

    Public Function GetUserAppClientAccessList() As String
    
        Dim fullPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        Dim appFolder = Path.Combine(fullPath, "your_app_reserved_folder")
        if Not Directory.Exists(appFolder) then
            Directory.Create(appFolder)
        End If
        return = Path.Combine(appFolder, "ClientAccessList.txt")
    End Function