You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构建自定义打开文件对话框:如何获取Windows Explorer收藏夹*.lnk列表?

获取Windows资源管理器收藏夹快捷方式列表的方法

嘿,这个需求我之前帮不少开发者处理过,其实Windows把资源管理器左侧窗格的收藏夹快捷方式(*.lnk)存在特定的系统路径里,而且我们可以通过两种方式来获取:直接读取文件系统,或者调用Windows Shell API来确保路径的准确性(毕竟有些用户可能自定义过收藏夹位置)。下面给你详细拆解:

一、直接读取用户级收藏夹路径

Windows默认把当前用户的收藏夹快捷方式放在这个路径下:

%USERPROFILE%\Links

你可以直接遍历这个文件夹里的所有.lnk文件,这些就是资源管理器左侧“收藏夹”里显示的项目(包括默认的“桌面”、“下载”、“文档”等,以及用户自己添加的快捷方式)。

示例代码(C#)

如果用.NET开发,你可以这样获取并遍历:

using System.IO;

string linksPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Links");
if (Directory.Exists(linksPath))
{
    // 获取所有.lnk文件,包括隐藏的系统默认项
    string[] lnkFiles = Directory.GetFiles(linksPath, "*.lnk", SearchOption.TopDirectoryOnly);
    foreach (string lnkPath in lnkFiles)
    {
        // 这里可以处理每个快捷方式文件,比如读取目标路径、显示名称等
        Console.WriteLine(Path.GetFileName(lnkPath));
    }
}

二、用Shell API获取准确路径(推荐)

如果担心用户修改了默认的收藏夹位置,最好调用Windows Shell的SHGetKnownFolderPath函数来获取官方的路径,对应的Known Folder ID是FOLDERID_Links。

示例代码(C# P/Invoke)

using System;
using System.Runtime.InteropServices;
using System.IO;

class KnownFolders
{
    [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
    private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);

    public static string GetLinksFolderPath()
    {
        // FOLDERID_Links的官方GUID
        Guid linksFolderId = new Guid("bfb9d5e0-c6a9-404c-b2b2-ae6db6af4968"); 
        IntPtr pathPtr = IntPtr.Zero;
        try
        {
            int result = SHGetKnownFolderPath(linksFolderId, 0, IntPtr.Zero, out pathPtr);
            if (result == 0)
            {
                return Marshal.PtrToStringUni(pathPtr);
            }
            else
            {
                throw new Exception($"获取收藏夹路径失败,错误代码: {result}");
            }
        }
        finally
        {
            if (pathPtr != IntPtr.Zero)
            {
                Marshal.FreeCoTaskMem(pathPtr);
            }
        }
    }
}

// 使用示例
string linksPath = KnownFolders.GetLinksFolderPath();
if (Directory.Exists(linksPath))
{
    string[] lnkFiles = Directory.GetFiles(linksPath, "*.lnk", SearchOption.TopDirectoryOnly);
    foreach (var lnk in lnkFiles)
    {
        // 在这里处理每个快捷方式文件
    }
}

三、解析快捷方式的详细信息

如果你还需要读取.lnk文件的目标路径、显示名称、图标等信息,可以借助IWshRuntimeLibrary COM组件来实现:

using IWshRuntimeLibrary;

WshShell shell = new WshShell();
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(lnkFilePath);
string targetPath = shortcut.TargetPath; // 获取快捷方式指向的目标路径
string iconPath = shortcut.IconLocation; // 获取图标路径

注意:使用这个组件需要在项目中添加对Windows Script Host Object Model的COM引用。


内容的提问来源于stack exchange,提问作者VA systems engineer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:51:06