创建文件快捷方式 (.lnk) [英] Creating a file shortcut (.lnk)

查看:64
本文介绍了创建文件快捷方式 (.lnk)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种在 C# 中创建文件快捷方式的简单方法,但我只找到了执行此操作的外部 dll.这实际上很令人惊讶,没有内置的方法可以做到这一点..

I have been looking for a simple way to create a shortcut to a file in C#, but I've only found external dlls that do that. It's actually quite surprising, there's no built in way to do that..

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

Anyway, I know that lnk files are just text files with a certain command and a given path. I thought that maybe I could create a text file (in the code) set it's text to the right command and change it's extension to .lnk I've tried to do that manually first, but failed to do so.

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

Is there a way to do something like that (or maybe another simple way) to create a shortcut to a certain path in c#?

为了清楚起见,快捷方式我的意思是一个 .lnk 文件,它指向该文件我所说的文件是指我想要的任何文件,而不仅仅是我自己的应用程序的快捷方式

如果它不适用于每个场景,我会进行编辑.

I'll edit if it doesn't work well for every scenario.

添加这些引用:

  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:UsersiminDesktop	est folder";            
shortcut.Save();

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

Hope it helps others as well, thanks for your attention.

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

Also, if there IS a way to create a file, write the right commands and then change it to an lnk file, please let me know.

推荐答案

Joepro 在 他们的回答:

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

You'll need to add a COM reference to Windows Scripting Host. As far as i know, there is no native .net way to do this.

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 及更高版本,将第一行替换为以下内容:

For .Net 4.0 and above, replace the first line with the following:

 WshShell wsh = new WshShell();

这个链接也有帮助

这篇关于创建文件快捷方式 (.lnk)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆