a12*_*773 6 c# console-application
我想获取当前目录路径,但不是应用程序位置,而是它的快捷方式位置.
我尝试了这些,但他们返回应用程序的位置.
Directory.GetCurrentDirectory();
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
Run Code Online (Sandbox Code Playgroud)
根据MSDN中的进程API参考,STARTUPINFO给定进程的进程结构体在标题成员中包含有关快捷方式.lnk文件的信息。在这种情况下,结构成员中存在一个标志dwFlags,该标志会被设置 - 所以看起来这并不总是被设置(我猜测如果您直接运行 exe)
来自 MSDN:
STARTF_TITLEIS 链接名称:0x00000800
lpTitle 成员包含用户调用以启动此进程的快捷方式文件 (.lnk) 的路径。这通常由 shell 在调用指向已启动应用程序的 .lnk 文件时设置。大多数应用程序不需要设置该值。该标志不能与 STARTF_TITLEISAPPID 一起使用。
参考这里。
如果添加COM对象引用不是问题,请添加COM对象引用 - Windows脚本宿主对象模型
我在我的桌面文件夹中运行此代码,它确实有效.对于当前文件夹使用 - Environment.CurrentDirectory
using System;
using System.IO;
using IWshRuntimeLibrary; //COM object -Windows Script Host Object Model
namespace csCon
{
class Program
{
static void Main(string[] args)
{
// Folder is set to Desktop
string dir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var di = new DirectoryInfo(dir);
FileInfo[] fis = di.GetFiles();
if (fis.Length > 0)
{
foreach (FileInfo fi in fis)
{
if (fi.FullName.EndsWith("lnk"))
{
IWshShell shell = new WshShell();
var lnk = shell.CreateShortcut(fi.FullName) as IWshShortcut;
if (lnk != null)
{
Console.WriteLine("Link name: {0}", lnk.FullName);
Console.WriteLine("link target: {0}", lnk.TargetPath);
Console.WriteLine("link working: {0}", lnk.WorkingDirectory);
Console.WriteLine("description: {0}", lnk.Description);
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)

论坛代码参考:http://www.neowin.net/forum/topic/658928-c%23-resolve-lnk-files/