我在一个未知文件夹(即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.TargetPathn"
};
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;
}