我在一个未知文件夹(即 c:\dev)中有一个 (.exe) 快捷方式,指向我的应用程序。
每当我的应用程序由快捷方式启动时,我一直在尝试获取快捷方式路径。
我尝试了不同的方法,例如 Application.StartupPath ,但它返回应用程序可执行文件的路径,而不是快捷方式的路径。
此代码将为您提供帮助。:)
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);
// This requires a COM Reference to Shell32 (Microsoft Shell Controls And Automation).
Shell shell = new Shell();
Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null && folderItem.IsLink)
{
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));
}
}
}
如果您需要从不同的快捷方式更改程序流程,请从每个快捷方式传递一个参数并在 main(args) 中读取它。
如果您只需要获取快捷方式文件夹,请确保“开始于”文本为空白并使用获取文件夹
Environment.CurrentDirectory
如果您不想在程序集中添加过时的 DLL,这里有一个解决方案:
private static string LnkToFile(string fileLink) {
List<string> saveout = new List<string>();
// KLUDGE Until M$ gets their $^%# together...
string[] vbs_script = {
"set WshShell = WScript.CreateObject(\"WScript.Shell\")\n",
"set Lnk = WshShell.CreateShortcut(WScript.Arguments.Unnamed(0))\n",
"wscript.Echo Lnk.TargetPath\n"
};
string tempPath = System.IO.Path.GetTempPath();
string tempFile = System.IO.Path.Combine(tempPath, "pathenator.vbs");
File.WriteAllLines(tempFile, vbs_script);
var scriptProc = new System.Diagnostics.Process();
scriptProc.StartInfo.FileName = @"cscript";
scriptProc.StartInfo.Arguments = " //nologo \""
+ tempFile + "\" \"" + fileLink + "\"";
scriptProc.StartInfo.CreateNoWindow = true;
scriptProc.StartInfo.UseShellExecute = false;
scriptProc.StartInfo.RedirectStandardOutput = true;
scriptProc.Start();
scriptProc.WaitForExit();
string lineall
= scriptProc.StandardOutput.ReadToEnd().Trim('\r', '\n', ' ', '\t');
scriptProc.Close();
return lineall;
}