例如,我在D:\AA\test.exe发送一个快捷方式到桌面,然后把这个快捷方式放到C:\BB目录内,双击C:\BB里的快捷方式,如何获取到C:\BB目录。一般的方法我测试出来获取到的都是D:\AA目录。还是说无法获取?
可能不行。因为快捷方式本身就是引用原来的文件,也就是说,运行快捷方式,只是换种方式运行原来的文件,目录是不会变的。但是可以尝试复制粘贴exe,准确一点,把bin下的所有文件复制到另一个地方,再运行,目录是会变的。
该回答引用ChatGPT
请参考下面的解决方案,如果有帮助,还请点击 “采纳” 感谢支持!
在 C# 中,您可以使用 System.Windows.Forms.Application.StartupPath 来获取当前程序启动目录,但这将得到程序可执行文件所在的目录,而不是快捷方式所在的目录。
如果您想要获取快捷方式所在的目录,可以使用以下代码:
using System;
using System.IO;
using System.Windows.Forms;
namespace GetShortcutPath
{
class Program
{
static void Main(string[] args)
{
string shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "test.lnk");
string targetPath = ResolveShortcut(shortcutPath);
Console.WriteLine(Path.GetDirectoryName(targetPath));
}
static string ResolveShortcut(string file)
{
WshShell shell = new WshShell();
IWshShortcut link = (IWshShortcut)shell.CreateShortcut(file);
return link.TargetPath;
}
}
}
需要引用 Windows Script Host Object Model,可以在 Visual Studio 中使用 NuGet 包管理器安装。