Search code examples
c#special-folders

Create shortcut in Favorites with filepath C#


I have the following code below. I can't seem to get it to work for adding a folder to favorites. If I change it to specialfolders.desktop, it creates a shortcut on the 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();
    }

enter image description here


Solution

  • Environment.SpecialFolder.Favorites represents the folder that contains your Internet Explorer favorites, which are located in the %USERPROFILE%\Favorites folder.

    There is no Environment.SpecialFolder value that represents your Windows Explorer favorites, which are located in the %USERPROFILE%\Links folder.

    To retrieve the path to the Links folder, you will have to query the Shell directly for the FOLDERID_Links path using either:

    1. PInvoke to call SHKnownFolderPath().

    2. COM interop to call IKnownFolderManager.GetFolder() and then IKnownFolder.GetPath().