14

I'm trying to locate the path for the AppData\LocalLow folder.

I have found an example which uses:

string folder = "c:\users\" + Environment.UserName + @"\appdata\LocalLow";

which for one is tied to c: and to users which seems a bit fragile.

I tried to use

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

but this gives me AppData\Local, and I need LocalLow due to the security constraints the application is running under. It returned blank for my service user as well (at least when attaching to the process).

Any other suggestions?

Mikael Svenson
  • 38,031
  • 6
  • 71
  • 73

2 Answers2

24

The Environment.SpecialFolder enumeration maps to CSIDL, but there is no CSIDL for the LocalLow folder. So you have to use the KNOWNFOLDERID instead, with the SHGetKnownFolderPath API:

void Main()
{
    Guid localLowId = new Guid("A520A1A4-1780-4FF6-BD18-167343C5AF16");
    GetKnownFolderPath(localLowId).Dump();
}

string GetKnownFolderPath(Guid knownFolderId)
{
    IntPtr pszPath = IntPtr.Zero;
    try
    {
        int hr = SHGetKnownFolderPath(knownFolderId, 0, IntPtr.Zero, out pszPath);
        if (hr >= 0)
            return Marshal.PtrToStringAuto(pszPath);
        throw Marshal.GetExceptionForHR(hr);
    }
    finally
    {
        if (pszPath != IntPtr.Zero)
            Marshal.FreeCoTaskMem(pszPath);
    }
}

[DllImport("shell32.dll")]
static extern int SHGetKnownFolderPath( [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);
Thomas Levesque
  • 278,830
  • 63
  • 599
  • 738
1

Thomas's answer is effective yet needlessly complex for some use cases.

A quick solution is:

string LocalLowPath = 
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).Replace("Roaming","LocalLow");
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 03 '22 at 06:47