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

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

我认为你需要使用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)); } } } 

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

如果您不想使用依赖项,可以使用https://blez.wordpress.com/2013/02/18/get-file-shortcuts-target-with-c/但是lnk格式没有文档,所以只做它如果你了解风险。

如果你想找到你的桌面上有快捷方式的应用程序路径,我使用的一种简单方法如下:

 Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\\") 

此代码返回正在运行的任何exe路径,无论谁请求文件

获取我使用的链接路径的更简单方法是:

 private static string LnkToFile(string fileLink) { string link = File.ReadAllText(fileLink); int i1 = link.IndexOf("DATA\0"); if (i1 < 0) return null; i1 += 5; int i2 = link.IndexOf("\0", i1); if (i2 < 0) return link.Substring(i1); else return link.Substring(i1, i2 - i1); } 

但是如果lnk文件格式发生变化,它当然会中断。

感谢Mohsen.Sharify的回答,我得到了更多整齐的代码:

 var fileName = Process.GetCurrentProcess().MainModule.FileName; var folderName = Path.Combine(fileName, ".."); //origin folder 

所有文件快捷方式都有一个.lnk文件扩展名,您可以查看。 例如,使用字符串,您可以使用string.EndsWith(“。lnk”)作为filter。

所有URL快捷方式都有.url文件扩展名,因此如果需要,您还需要考虑这些内容。