【问题标题】:Creating a file shortcut (.lnk)创建文件快捷方式 (.lnk)
【发布时间】:2013-08-04 02:34:01
【问题描述】:

我一直在寻找一种在 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:\Users\Zimin\Desktop\test folder";            
shortcut.Save();

希望对其他人也有帮助,感谢您的关注。

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

【问题讨论】:

标签: c# automation shortcut lnk


【解决方案1】:

Joepro 在their answer here 中指出了一种方法:

您需要添加对 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();

编辑: This link can help too

【讨论】:

  • 这似乎没问题,我已经看过了.. 我只是想到了别的东西...但是如果这允许我这样做并且没有更好的方法,我会尝试并使用它我猜。
  • 在引用 Windows 脚本主机时,“嵌入互操作类型”也应设置为 false。否则你会得到类型 'IWshRuntimeLibrary.WshShellClass' has no constructors defined
  • 添加参考 > COM > Windows 脚本宿主对象模型
猜你喜欢
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-26
  • 2010-09-25
相关资源
最近更新 更多