Accessing %appdata% with VB.NET

Viewed 53400

How can you access files in %appdata% through VB.NET?

For example, C:\Users\Kuzon\AppData\Roaming\program. How would I access that file, but on another Windows 7 machine? Also, how would you do it on Windows XP? I believe it is %Application Data%.

4 Answers

It's not only knowing where the application data are, but rather, allowing users to set which folder they want to be used as default. Some users aren't administrators, and can only use local or roaming, but you really don't know, so you have to use Try..Catch. Also, other users may need to use a network to access data, so their working folder is Roaming.

For any user, I allow them set their working directory, and also allow for a custom folder, which is usually for people with their own PC/laptop, who are their own administrator. Below are just the My.Settings commands.

I also create an OutputDirectory (folder) into which application results are saved. (they will have disk read & write privileges if they can access the parent working directory in use). If not, they have to get their IT to set their privileges.

    Dim mdfolder As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\Company Name"
    If Directory.Exists(mdfolder) = False Then Directory.CreateDirectory(mdfolder)
    Dim expfolder As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\Company Name\AppName"
    If Directory.Exists(expfolder) = False Then Directory.CreateDirectory(expfolder)
    My.Settings.MyDocumentsFolder = expfolder
    mdfolder = expfolder
    My.Settings.Save()

    Dim roamfolder As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\AppName"
    My.Settings.RoamingDataFolder = roamfolder
    My.Settings.Save()

    If My.Settings.DefaultDataFolderOption = 1 Then
        DefaultDataFolder = roamfolder
    End If
    If My.Settings.DefaultDataFolderOption = 2 Then
        DefaultDataFolder = mdfolder
    End If
    If My.Settings.DefaultDataFolderOption = 3 Then
        DefaultDataFolder = My.Settings.CustomDataFolder
    End If
    If DefaultDataFolder = "" Then
        DefaultDataFolder = mdfolder
    End If
    If OutputDirectory = "" Then OutputDirectory = DefaultDataFolder & "\Output"
Related