如何通过windows命令创建文件链接,并定义该链接的起始目录



我需要为我的应用程序创建一个快捷方式,并且该快捷方式需要具有相同的图标,因此不考虑使用bat文件来代替快捷方式。我还想要一个本机windows解决方案或.NET 5.0解决方案,而不是第三方程序,我希望尽可能低源代码。

我尝试过mklink,但它不提供设置快捷方式"的选项;起始位置:";目录,这对我的应用程序至关重要,我需要为其创建快捷方式。

这是我为自己制作的:

public class DesktopUtility : IDesktopUtility
{
public void CreateShortcut(string targetPath, string shortcutLinkPath)
{
if (!shortcutLinkPath.EndsWith(".lnk"))
shortcutLinkPath += ".lnk";
CreateShortcutVBS(targetPath, shortcutLinkPath);
if (!File.Exists(shortcutLinkPath))
CreateShortcutPS(targetPath, shortcutLinkPath);
}
public void CreateShortcutVBS(string targetPath, string shortcutLinkPath)
{
if (!shortcutLinkPath.EndsWith(".lnk"))
shortcutLinkPath += ".lnk";
var workingDirectory = Path.GetDirectoryName(targetPath);
var vbShortcutScript = "Set oWS = WScript.CreateObject("WScript.Shell")n" +
$"sLinkFile = "{shortcutLinkPath}"n" +
"Set oLink = oWS.CreateShortcut(sLinkFile) n" +
$"oLink.TargetPath = "{targetPath}"n" +
$"oLink.WorkingDirectory = "{workingDirectory}"n" +
"oLink.Save";
var fileName = Path.GetFileNameWithoutExtension(targetPath);
var scriptFilePath = Path.Combine(workingDirectory, $"{fileName}.vbs");
//var wscriptPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"System32wscript.exe");
try
{
using (var file = File.CreateText(scriptFilePath))
file.Write(vbShortcutScript);
var psi = new ProcessStartInfo
{
FileName = "wscript.exe",
UseShellExecute = false,
Arguments= $"/b "{scriptFilePath}""
};
Process.Start(psi).WaitForExit();
}
finally
{
if (File.Exists(scriptFilePath))
File.Delete(scriptFilePath);
}
}
public void CreateShortcutPS(string targetPath, string shortcutLinkPath)
{
if (!shortcutLinkPath.EndsWith(".lnk"))
shortcutLinkPath += ".lnk";
var workingDirectory = Path.GetDirectoryName(targetPath);
var psi = new ProcessStartInfo
{
FileName = "powershell.exe",
WindowStyle = ProcessWindowStyle.Hidden
};
psi.Arguments =
"-windowstyle hidden  " +
"$WshShell=New-Object -comObject WScript.Shell; " +
$"$LinkPath = \"{shortcutLinkPath}\"; " +
$"$Shortcut = $WshShell.CreateShortcut($LinkPath); " +
$"$Shortcut.TargetPath = \"{ targetPath}\"; " +
$"$Shortcut.WorkingDirectory = \"{workingDirectory}\"; " +
"$Shortcut.Save();";
Process.Start(psi).WaitForExit();
}
}

我不喜欢PowerShell方法,因为它简单地显示了窗口,我希望能够内联执行vbscript,而不是通过文件,不知道如何执行。

最新更新