[英]Creating a file shortcut (.lnk)
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. 我一直在寻找一种在C#中创建文件快捷方式的简单方法,但我只找到了那样做的外部dll。 It's actually quite surprising, there's no built in way to do that..
这实际上是相当令人惊讶的,没有内置的方法来做到这一点..
Anyway, I know that lnk files are just text files with a certain command and a given path. 无论如何,我知道lnk文件只是具有特定命令和给定路径的文本文件。 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.
我想也许我可以创建一个文本文件(在代码中)将它的文本设置为正确的命令并将其扩展名更改为.lnk我尝试先手动执行此操作,但未能这样做。
Is there a way to do something like that (or maybe another simple way) to create a shortcut to a certain path in c#? 有没有办法做这样的事情(或者可能是另一种简单的方法)来创建c#中某个路径的快捷方式?
Just to be clear, by Shortcut I mean an .lnk file that leads to the file Edit: And by file I mean any file I'd want, not only a shortcut to my own application 为了清楚起见,通过快捷方式我的意思是一个.lnk文件,它导致文件 编辑:而文件我指的是我想要的任何文件,而不仅仅是我自己的应用程序的快捷方式
I'll edit if it doesn't work well for every scenario. 如果它不适合每个场景,我会编辑。
Add these references: 添加以下参考:
Add this namespaces: 添加此命名空间:
using Shell32;
using IWshRuntimeLibrary;
Next appears to be working: 接下来似乎工作:
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();
Hope it helps others as well, thanks for your attention. 希望它能帮助其他人,感谢您的关注。
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. 另外,如果有一种创建文件的方法,请编写正确的命令,然后将其更改为lnk文件,请告诉我。
One way to do this is pointed out by Joepro in their answer here : Joepro在答案中指出了一种方法:
You'll need to add a COM reference to Windows Scripting Host.
您需要向Windows Scripting Host添加COM引用。 As far as i know, there is no native .net way to do this.
据我所知,没有原生的.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();
For .Net 4.0 and above, replace the first line with the following: 对于.Net 4.0及更高版本,请使用以下内容替换第一行:
WshShell wsh = new WshShell();
EDIT: This link can help too 编辑: 此链接也可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.