如何在C#中创建一个相对路径的Windows快捷方式?

11 浏览
0 Comments

如何在C#中创建一个相对路径的Windows快捷方式?

我正在尝试结合两个问题:1) 如何在Windows中创建相对快捷方式和2) 如何使用C#创建Windows快捷方式

我有以下代码用于创建快捷方式(基于我看到的问题),但在分配shortcut.TargetPath时抛出异常:“值不在预期的范围内”

public void CreateShortcut() {
    IWshRuntimeLibrary.WshShell wsh = new IWshRuntimeLibrary.WshShell();
    IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(Path.Combine(outputFolder, "sc.lnk")) as IWshRuntimeLibrary.IWshShortcut;
    shortcut.Arguments = "";
    shortcut.TargetPath = "%windir%\\system32\\cmd.exe /c start \"\" \"%CD%\\folder\\executable.exe\"";
    shortcut.WindowStyle = 1;
    shortcut.Description = "executable";
    shortcut.WorkingDirectory = "%CD%";
    shortcut.IconLocation = "";
    shortcut.Save();
}

如何修复这个问题并创建相对快捷方式?

注意:我不想编写批处理脚本来完成此操作,因为我的软件很可能安装在用户无法访问命令行的PC上 - 我们的客户通常有非常受限的机器,并且几乎肯定没有执行批处理文件的权限。如果您有任何关于如何创建一个“便携”文件夹(其中我的.exe在子文件夹中)的建议,用户只需双击顶级文件夹中的某个东西即可运行exe,我愿意听取建议!

0
0 Comments

问题的原因是在Windows快捷方式中无法在TargetPath属性中添加参数。解决方法是将参数放入Arguments属性中,并使用IWshRuntimeLibrary库创建快捷方式。以下是解决方法的代码示例:

public void CreateShortcut() {
    IWshRuntimeLibrary.WshShell wsh = new IWshRuntimeLibrary.WshShell();
    IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(Path.Combine(outputFolder, "sc.lnk")) as IWshRuntimeLibrary.IWshShortcut;
    shortcut.Arguments = "/c start \"\" \"%CD%\\folder\\executable.exe\"";
    shortcut.TargetPath = "%windir%\\system32\\cmd.exe";
    shortcut.WindowStyle = 1;
    shortcut.Description = "executable";
    shortcut.WorkingDirectory = "%CD%";
    shortcut.IconLocation = "P:\ath\to\any\icon.ico";
    shortcut.Save();
}

这段代码使用IWshRuntimeLibrary库中的WshShell类创建了一个快捷方式对象shortcut,并将其Arguments属性设置为包含参数的字符串。TargetPath属性指定了快捷方式的目标路径,WindowStyle属性设置了窗口样式,Description属性设置了快捷方式的描述,WorkingDirectory属性设置了快捷方式的工作目录,IconLocation属性指定了快捷方式的图标路径。最后,调用Save()方法保存快捷方式。

0