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

use*_*803 20 c# automation shortcut lnk

我一直在寻找一种在C#中创建文件快捷方式的简单方法,但我只找到了那样做的外部dll.这实际上是相当令人惊讶的,没有内置的方法来做到这一点..

无论如何,我知道lnk文件只是具有特定命令和给定路径的文本文件.我想也许我可以创建一个文本文件(在代码中)将它的文本设置为正确的命令并将其扩展名更改为.lnk我尝试先手动执行此操作,但未能这样做.

有没有办法做这样的事情(或者可能是另一种简单的方法)来创建c#中某个路径的快捷方式?

为了清楚起见,通过快捷方式我的意思是一个.lnk文件,它导致文件 编辑:而文件我指的是我想要的任何文件,而不仅仅是我自己的应用程序的快捷方式


如果它不适合每个场景,我会编辑.

添加以下参考:

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

添加此命名空间:

using Shell32;
using IWshRuntimeLibrary;
Run Code Online (Sandbox Code Playgroud)

接下来似乎工作:

var wsh = new IWshShell_Class();
IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\shorcut2.lnk") as IWshRuntimeLibrary.IWshShortcut;
shortcut.TargetPath = @"C:\Users\Zimin\Desktop\test folder";            
shortcut.Save();
Run Code Online (Sandbox Code Playgroud)

希望它能帮助其他人,感谢您的关注.

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

Dan*_*eda 15

Joepro在答案中指出了一种方法:

您需要向Windows Scripting Host添加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();
Run Code Online (Sandbox Code Playgroud)

对于.Net 4.0及更高版本,请使用以下内容替换第一行:

 WshShell wsh = new WshShell();
Run Code Online (Sandbox Code Playgroud)

编辑: 此链接也可以帮助

  • 在引用Windows Scripting Host时,"Embed Interop Types"也应设置为false.否则你会得到类型'IWshRuntimeLibrary.WshShellClass'没有定义构造函数 (3认同)
  • 添加引用> COM> Windows脚本宿主对象模型 (3认同)