Create Shortcut in .Net for 64-Bit Machines - Comp

2020-05-06 11:27发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
Creating application shortcut in a directory

There is a lot of code floating around showing how to create a shortcut in .Net, but it only works when compiled as a 32 bit application. You can't use IWshRuntimeLibrary.WshShell in a 64 bit application.

Does anyone know how to create short-cuts in 64 bit applications?

Note, I'm not looking for a way to do it while installing either. This is for post-install purposes.

And I'm aware of this post on SO (Create shortcut from vb.net on Windows 7 box (64 bit)), but it's not the correct answer for the question. The question is 64-bit and the person gave a 32-bit answer and said "just compile 32-bit".

回答1:

You don't need to use special libraries to create the shortcut, you can use the Shell32 automation object directly from a C# or VB.NET program. Get started with Project + Add Reference, Browse tab, select c:\windows\system32\shell32.dll

Then write code like this to create the .lnk file:

    // Creating a link named "test" on the desktop
    string lnkDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
    string lnkName = "test";

    // Create an empty .lnk file so we can create an object for it
    string lnkPath = System.IO.Path.Combine(lnkDir, lnkName) + ".lnk";
    System.IO.File.WriteAllBytes(lnkPath, new byte[] { });

    // Initialize a ShellLinkObject for that .lnk file
    Shell32.Shell shl = new Shell32.ShellClass();
    Shell32.Folder dir = shl.NameSpace(lnkDir);
    Shell32.FolderItem itm = dir.Items().Item(lnkName + ".lnk");
    Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)itm.GetLink;

    // We'll just dummy a link to notepad
    lnk.Path = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\notepad.exe";
    lnk.Description = "Anything goes here";
    lnk.Arguments = @"c:\sample.txt";
    lnk.WorkingDirectory = @"c:\";

    // And dummy an icon (it will the one used by cmd.exe)
    lnk.SetIconLocation(Environment.GetFolderPath(Environment.SpecialFolder.System) + "cmd.exe", 1);

    // Done, save it
    lnk.Save(lnkPath);


回答2:

I suggest you to use COM instead of WScript to create your shortcuts.
Take a look at this tutorial : Creating and Modifying Shortcuts
You will find the ShellLink .NET Class that let you manipulate shortcuts.