【问题标题】:Detect the location of AppData\LocalLow检测 AppData\LocalLow 的位置
【发布时间】:2010-12-20 21:49:51
【问题描述】:

我正在尝试查找 AppData\LocalLow 文件夹的路径。

我找到了一个例子,它使用:

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

其中一个与c:users 相关联,这似乎有点脆弱。

我尝试使用

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

但这给了我AppData\Local,由于应用程序运行时的安全限制,我需要LocalLow。它也为我的服务用户返回空白(至少在附加到进程时)。

还有其他建议吗?

【问题讨论】:

  • 有什么原因不能将Low 附加到返回的字符串?
  • Path.Combine(localData, @"..\LocalLow")
  • 当然我可以追加低或使用路径组合,但我认为@Thomas 解决方案是最好的。由于它已经是一个操作系统调用,我宁愿使用它。
  • 除非 Microsoft 已承诺在非英语版本的 Windows 中保留“LocalLow”作为名称,否则首选操作系统调用似乎是个好主意...

标签: c# .net


【解决方案1】:

Environment.SpecialFolder 枚举映射到CSIDL,但LocalLow 文件夹没有CSIDL。所以你必须改用KNOWNFOLDERIDSHGetKnownFolderPath 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);

【讨论】:

  • 如何知道 A520A1A4-1780-4FF6-BD18-167343C5AF16 ?
  • Dump 是什么?
  • @Kiquenet GUID 是一个KNOWNFOLDERID 常量(参见链接)。 Dump 是来自 LinqPad 的用于显示值的方法。
【解决方案2】:

Thomas 的回答是有效的,但对于某些用例来说是不必要的复杂。

一个快速的解决方案是:

string LocalLowPath = 
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).Replace("Roaming","LocalLow");

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 2019-03-26
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多