获取快捷方式文件夹的目标

Phu*_*ham 16 c# directory shortcut target

你如何获得快捷方式文件夹的目录目标?我到处搜索,只找到快捷方式文件的目标.

Luk*_*vin 23

我认为你需要使用COM并添加对"Microsoft Shell Control And Automation"的引用,如本博文中所述:

以下是使用此处提供的代码的示例:

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我在Windows 7 64位上工作,它无法找到安装在`C:\ Program Files\Oracle\VirtualBoxOSX`中的VirtualBox的快捷方式.它一直将目标返回到`C:\ Program Files(x86)\ Oracle\VirtualBoxOSX\VirtualBox.exe`.有关此行为的任何解释? (3认同)
  • 将 Shell32 与此方法一起使用仅允许在单线程应用程序中使用。您必须在主入口点中包含 [STAThread]。您将在使用此代码进行单元测试时遇到异常,因为单元测试不允许 STAThread。请参阅[答案](http://stackoverflow.com/questions/14543340/calling-shell32-dl​​l-from-net-windows-service)。还有在单元测试中运行此代码的解决方案,请参见 http://haacked.com/archive/2014/11/20/xunit-and-sta/ (2认同)

EJ *_*yer 7

在Windows 10中,需要像这样完成,首先将COM引用添加到“Microsoft Shell Control And Automation”

// new way for windows 10
string targetname;
string pathOnly = System.IO.Path.GetDirectoryName(LnkFileName);
string filenameOnly = System.IO.Path.GetFileName(LnkFileName);

Shell shell = new Shell();
Shell32.Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null) {
  Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  targetname = link.Target.Path;  // <-- main difference
  if (targetname.StartsWith("{")) { // it is prefixed with {54A35DE2-guid-for-program-files-x86-QZ32BP4}
    int endguid = targetname.IndexOf("}");
    if (endguid > 0) {
      targetname = "C:\\program files (x86)" + targetname.Substring(endguid + 1);
  }
}
Run Code Online (Sandbox Code Playgroud)