如何通过编程将.lnk文件的目标更改?

8
有没有办法打开Windows快捷方式(.lnk文件)并更改其目标?我找到了下面的代码片段,它允许我找到当前的目标,但它是只读属性:
Shell32::Shell^ shl = gcnew Shell32::Shell();
String^ shortcutPos = "C:\\some\\path\\to\\my\\link.lnk";
String^ lnkPath = System::IO::Path::GetFullPath(shortcutPos);
Shell32::Folder^ dir = shl->NameSpace(System::IO::Path::GetDirectoryName(lnkPath));
Shell32::FolderItem^ itm = dir->Items()->Item(System::IO::Path::GetFileName(lnkPath));
Shell32::ShellLinkObject^ lnk = (Shell32::ShellLinkObject^)itm->GetLink;
String^ target = lnk->Target->Path;

我找不到任何可以更改目标的内容。我的唯一选择是创建一个新的快捷方式来覆盖当前的快捷方式吗?如果是这样,我该如何做呢?

2个回答

14

使用WSH重新创建快捷方式

您可以删除现有的快捷方式,并创建一个新的,具有新目标的快捷方式。为了创建一个新的快捷方式,您可以使用以下代码片段:

public void CreateLink(string shortcutFullPath, string target)
{
    WshShell wshShell = new WshShell();
    IWshRuntimeLibrary.IWshShortcut newShortcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(shortcutFullPath);
    newShortcut.TargetPath = target;
    newShortcut.Save();
}

目前,我没有看到更改目标路径的方法,除非重新创建快捷方式。

注意:要使用此片段,您必须将Windows Script Host Object Model COM添加到项目引用中。

使用Shell32更改目标路径

以下是一段可以在不删除和重新创建快捷方式的情况下更改其目标的代码片段:

public void ChangeLinkTarget(string shortcutFullPath, string newTarget)
{
    // Load the shortcut.
    Shell32.Shell shell = new Shell32.Shell();
    Shell32.Folder folder = shell.NameSpace(Path.GetDirectoryName(shortcutFullPath));
    Shell32.FolderItem folderItem = folder.Items().Item(Path.GetFileName(shortcutFullPath));
    Shell32.ShellLinkObject currentLink = (Shell32.ShellLinkObject)folderItem.GetLink;

    // Assign the new path here. This value is not read-only.
    currentLink.Path = newTarget;

    // Save the link to commit the changes.
    currentLink.Save();
}

第二个可能是你需要的。

注意:抱歉,这些代码片段是用C#编写的,因为我不知道C ++ / CLI。如果有人想重新编写这些代码片段以供C ++ / CLI使用,请随意编辑我的答案。


2
请参考此处了解如何引用Shell32。 - huha

13

它不是只读的,使用lnk->Path代替,然后进行lnk->Save()。假设您对该文件具有写权限。在此线程中,我的答案中提供了相同功能的C#代码。


这对C#也非常有效,但是要访问Shell32.Shell类,我必须在我的项目中添加C:\ Windows \ system32 \ shell32.dll作为引用。 - Gabe Halsmer
这很不错,但我怎样才能使用它来仅读取受保护的文件呢? - Adam L. S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接