Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

c# - Detect the location of AppDataLocalLow

I'm trying to locate the path for the AppDataLocalLow folder.

I have found an example which uses:

string folder = "c:users" + Environment.UserName + @"appdataLocalLow";

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 AppDataLocal, 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...