从ExecutableFile.exe快捷方式获取路径

时间:2013-08-21 09:07:32

标签: c# windows forms path shortcut

我在未知文件夹(即c:\ dev)中有一个(.exe)快捷方式,指向我的应用程序。

我一直试图通过快捷方式启动应用程序时获取快捷方式路径。

我尝试过像Application.StartupPath这样的不同方法,但它返回应用程序可执行文件的路径,而不是快捷方式的路径。

3 个答案:

答案 0 :(得分:0)

此代码可以帮助您。 :)

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

答案 1 :(得分:0)

如果您需要从不同的快捷方式更改程序的流程,则从每个快捷方式传递参数并在main(args)中读取它。

如果您只需要获取快捷方式文件夹,请确保“开始”文本为空并使用

获取文件夹
Environment.CurrentDirectory

答案 2 :(得分:0)

如果您不想将过时的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;
}