Search code examples
c#directorytargetshortcut

Get target of shortcut folder


How do you get the directory target of a shortcut folder? I've search everywhere and only finds target of shortcut file.


Solution

  • I think you will need to use COM and add a reference to "Microsoft Shell Control And Automation", as described in this answer.

    Here's example code to use it (from the now defunct http://www.saunalahti.fi/janij/blog/2006-12.html#d6d9c7ee-82f9-4781-8594-152efecddae2 ):

    namespace Shortcut
    {
        using System;
        using System.Diagnostics;
        using System.IO;
        using Shell32;
    
        class Program
        {
            public static string GetShortcutTargetFile(string shortcutFilename)
            {
                string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
                string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
    
                Shell shell = new Shell();
                Folder folder = shell.NameSpace(pathOnly);
                FolderItem folderItem = folder.ParseName(filenameOnly);
                if (folderItem != null)
                {
                    Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
                    return link.Path;
                }
    
                return string.Empty;
            }
    
            static void Main(string[] args)
            {
                const string path = @"C:\link to foobar.lnk";
                Console.WriteLine(GetShortcutTargetFile(path));
            }
        }
    }