正在创建文件快捷方式(.lnk)



我一直在寻找一种简单的方法来创建C#中文件的快捷方式,但我只找到了外部dll。事实上,这很令人惊讶,没有现成的方法来做到这一点。。

无论如何,我知道lnk文件只是具有特定命令和给定路径的文本文件。我想也许我可以创建一个文本文件(在代码中),将其文本设置为正确的命令,并将其扩展名更改为.lnk我试过先手动完成,但没有成功

有没有一种方法可以这样做(或者其他简单的方法),在c#中创建一个指向某个路径的快捷方式?

需要明确的是,我所说的快捷方式是指指向该文件的.lnk文件 编辑:我所说的文件是指我想要的任何文件,而不仅仅是我自己应用程序的快捷方式


如果它不能很好地适用于每个场景,我将进行编辑。

添加这些参考:

  1. Microsoft Shell控件和自动化
  2. Windows脚本主机对象模型

添加此命名空间:

using Shell32;
using IWshRuntimeLibrary;

下一个似乎正在工作:

var wsh = new IWshShell_Class();
IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\shorcut2.lnk") as IWshRuntimeLibrary.IWshShortcut;
shortcut.TargetPath = @"C:UsersZiminDesktoptest folder";            
shortcut.Save();

希望它也能帮助其他人,谢谢你的关注。

此外,如果有一种方法可以创建一个文件,编写正确的命令,然后将其更改为lnk文件,请告诉我。

Joepro在这里的回答中指出了一种实现这一点的方法:

您需要添加对Windows脚本主机的COM引用。据我所知,没有原生的.net方法可以做到这一点。

WshShellClass wsh = new WshShellClass();
IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\shorcut.lnk") as IWshRuntimeLibrary.IWshShortcut;
shortcut.Arguments = "";
shortcut.TargetPath = "c:\app\myftp.exe";
// not sure about what this is for
shortcut.WindowStyle = 1; 
shortcut.Description = "my shortcut description";
shortcut.WorkingDirectory = "c:\app";
shortcut.IconLocation = "specify icon location";
shortcut.Save();

对于.Net 4.0及以上版本,请将第一行替换为以下内容:

 WshShell wsh = new WshShell();

编辑:这个链接也可以帮助

最新更新