Get target of shortcut folder

前端 未结 7 802
名媛妹妹
名媛妹妹 2020-11-27 19:31

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

7条回答
  •  我在风中等你
    2020-11-27 20:03

    I think you will need to use COM and add a reference to "Microsoft Shell Control And Automation", as described in this blog post:

    Here's an example using the code provided there:

    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));
            }
        }
    }
    

提交回复
热议问题