2010-12-20 104 views
11

我試圖找到AppData\LocalLow文件夾的路徑。檢測AppData LocalLow的位置

我發現它使用一個例子:

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

這對於一個依賴於c:users這似乎有點脆弱。

我試圖用

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) 

,但是這給了我AppData\Local,我需要LocalLow由於應用程序在其下運行的安全約束。它也爲我的服務用戶返回空白(至少在附加到進程時)。

其他建議?

+0

有沒有什麼不能appent一個'Low'到返回的字符串理由嗎? – Oded 2010-12-20 21:55:41

+0

或'Path.Combine(localData,@「.. \ LocalLow」)' – 2010-12-20 21:57:31

+0

當然我可以追加低或使用路徑組合,但我認爲@Thomas解決方案是最好的。由於它已經是一個操作系統調用,我寧願使用它。 – 2010-12-22 08:59:59

回答

18

Environment.SpecialFolder枚舉映射到CSIDL,但LocalLow文件夾沒有CSIDL。所以,你必須使用KNOWNFOLDERID,隨之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); 
+0

正是我在找:) – 2010-12-22 08:59:03