Search code examples
c#appdata

C# How to get the User AppData folder, NOT AppData\Roaming?


I used below code to get the user's AppData folder -

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) 

But what I got is "C:\Users\(users)\AppData\Roaming". Is there a way to only get "C:\Users\(users)\AppData"?


Solution

  • First of all, accessing that folder directly is probably not a good idea unless Microsoft has published an API to retrieve its location. This means that there are no guarantees that this folder will even exist.

    If you for some reason really want to retrieve this folder, you could probably do something along the lines of

    Directory.GetParent(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))
    

    Then to verify, you could also retrieve e.g.

    Directory.GetParent(
        Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData))
    

    If the two are the same, it is likely the folder you want to find.

    But again, it is probably a good idea to question the motivation on why you need this path in the first place.