使用文件路径 C# 在收藏夹中创建快捷方式

Create shortcut in Favorites with filepath C#

我有下面的代码。我似乎无法将文件夹添加到收藏夹。如果我将其更改为 specialfolders.desktop,它会在桌面上创建一个快捷方式。

private void buttonAddFav_Click(object sender, EventArgs e)
    {
        string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
        string targetPath = listFolderResults.SelectedItem.ToString();
        var wsh = new IWshShell_Class();
        IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(
            Environment.GetFolderPath(Environment.SpecialFolder.Favorites) + "\shorcut2.lnk") as IWshRuntimeLibrary.IWshShortcut;
        shortcut.TargetPath = targetPath;
        shortcut.Save();
    }

Environment.SpecialFolder.Favorites 表示包含您的 Internet Explorer 收藏夹 的文件夹,它们位于 %USERPROFILE%\Favorites 文件夹中。

没有 Environment.SpecialFolder 值代表您的 Windows Explorer 收藏夹,它们位于 %USERPROFILE%\Links 文件夹中。

要检索 Links 文件夹的路径,您必须使用以下任一方法直接查询 Shell 以获得 FOLDERID_Links 路径:

  1. PInvoke 调用 SHKnownFolderPath().

  2. COM 互操作调用 IKnownFolderManager.GetFolder() and then IKnownFolder.GetPath().

下面的代码最终对我有用。下面的答案有助于确定我需要围绕 %userprofile%\links 构建,但 %userprofile% 在保存时给了我错误。当我使用下面的方法时,它起作用了。

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
        string targetPath = listFolderResults.SelectedItem.ToString();
        string shortcutPath = string.Format(@"C:\Users\{0}\Links",Environment.UserName);
        MessageBox.Show(shortcutPath);

        var wsh = new IWshShell_Class();
        IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(
            shortcutPath + string.Format(@"\{0}.lnk",textFavName.Text)) as IWshRuntimeLibrary.IWshShortcut;
        shortcut.TargetPath = targetPath;
        shortcut.Save();