C# 在目录中创建应用程序快捷方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/234231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating application shortcut in a directory
提问by Chasler
How do you create an application shortcut (.lnk file) in C# or using the .NET framework?
如何在 C# 中或使用 .NET 框架创建应用程序快捷方式(.lnk 文件)?
The result would be a .lnk file to the specified application or URL.
结果将是指定应用程序或 URL 的 .lnk 文件。
采纳答案by Chasler
It's not as simple as I'd have liked, but there is a great class call ShellLink.csat vbAccelerator
这不是那么简单,我会很喜欢,但有一个很大的一流的呼叫ShellLink.cs在 vbAccelerator
This code uses interop, but does not rely on WSH.
此代码使用互操作,但不依赖于 WSH。
Using this class, the code to create the shortcut is:
使用这个类,创建快捷方式的代码是:
private static void configStep_addShortcutToStartupGroup()
{
using (ShellLink shortcut = new ShellLink())
{
shortcut.Target = Application.ExecutablePath;
shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
shortcut.Description = "My Shorcut Name Here";
shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
shortcut.Save(STARTUP_SHORTCUT_FILEPATH);
}
}
回答by Anuraj
I found something like this:
我发现了这样的东西:
private void appShortcutToDesktop(string linkName)
{
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
using (StreamWriter writer = new StreamWriter(deskDir + "\" + linkName + ".url"))
{
string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=file:///" + app);
writer.WriteLine("IconIndex=0");
string icon = app.Replace('\', '/');
writer.WriteLine("IconFile=" + icon);
writer.Flush();
}
}
Original code at sorrowman's article "url-link-to-desktop"
回答by IllidanS4 wants Monica back
Nice and clean. (.NET 4.0)
漂亮干净。( .NET 4.0)
Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object
dynamic shell = Activator.CreateInstance(t);
try{
var lnk = shell.CreateShortcut("sc.lnk");
try{
lnk.TargetPath = @"C:\something";
lnk.IconLocation = "shell32.dll, 1";
lnk.Save();
}finally{
Marshal.FinalReleaseComObject(lnk);
}
}finally{
Marshal.FinalReleaseComObject(shell);
}
That's it, no additional code needed. CreateShortcutcan even load shortcut from file, so properties like TargetPathreturn existing information. Shortcut object properties.
就是这样,不需要额外的代码。CreateShortcut甚至可以从文件加载快捷方式,因此TargetPath 等属性返回现有信息。快捷方式对象属性。
Also possible this way for versions of .NET unsupporting dynamic types. (.NET 3.5)
对于不支持动态类型的 .NET 版本,也可以采用这种方式。( .NET 3.5)
Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object
object shell = Activator.CreateInstance(t);
try{
object lnk = t.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell, new object[]{"sc.lnk"});
try{
t.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk, new object[]{@"C:\whatever"});
t.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk, new object[]{"shell32.dll, 5"});
t.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null);
}finally{
Marshal.FinalReleaseComObject(lnk);
}
}finally{
Marshal.FinalReleaseComObject(shell);
}
回答by AZ_
You also need to import of COM library IWshRuntimeLibrary
. Right click on your project -> add reference -> COM -> IWshRuntimeLibrary -> add and then use the following code snippet.
您还需要导入 COM 库IWshRuntimeLibrary
。右键单击您的项目 -> 添加引用 -> COM -> IWshRuntimeLibrary -> 添加,然后使用以下代码片段。
private void createShortcutOnDesktop(String executablePath)
{
// Create a new instance of WshShellClass
WshShell lib = new WshShellClass();
// Create the shortcut
IWshRuntimeLibrary.IWshShortcut MyShortcut;
// Choose the path for the shortcut
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
MyShortcut = (IWshRuntimeLibrary.IWshShortcut)lib.CreateShortcut(@deskDir+"\AZ.lnk");
// Where the shortcut should point to
//MyShortcut.TargetPath = Application.ExecutablePath;
MyShortcut.TargetPath = @executablePath;
// Description for the shortcut
MyShortcut.Description = "Launch AZ Client";
StreamWriter writer = new StreamWriter(@"D:\AZ\logo.ico");
Properties.Resources.system.Save(writer.BaseStream);
writer.Flush();
writer.Close();
// Location for the shortcut's icon
MyShortcut.IconLocation = @"D:\AZ\logo.ico";
// Create the shortcut at the given path
MyShortcut.Save();
}
回答by Ohad Schneider
After surveying all possibilities I found on SO I've settled on ShellLink:
在调查了我在 SO 上发现的所有可能性之后,我决定使用ShellLink:
//Create new shortcut
using (var shellShortcut = new ShellShortcut(newShortcutPath)
{
Path = path
WorkingDirectory = workingDir,
Arguments = args,
IconPath = iconPath,
IconIndex = iconIndex,
Description = description,
})
{
shellShortcut.Save();
}
//Read existing shortcut
using (var shellShortcut = new ShellShortcut(existingShortcut))
{
path = shellShortcut.Path;
args = shellShortcut.Arguments;
workingDir = shellShortcut.WorkingDirectory;
...
}
Apart of being simple and effective, the author (Mattias Sj?gren, MS MVP) is some sort of COM/PInvoke/Interop guru, and perusing his code I believe it is more robust than the alternatives.
除了简单有效之外,作者(Mattias Sj?gren,MS MVP)还是某种 COM/PInvoke/Interop 大师,仔细阅读他的代码,我相信它比替代方案更健壮。
It should be mentioned that shortcut files can also be created by several commandline utilities (which in turn can be easily invoked from C#/.NET). I never tried any of them, but I'd start with NirCmd(NirSoft have SysInternals-like quality tools).
应该提到的是,快捷方式文件也可以由几个命令行实用程序创建(反过来可以很容易地从 C#/.NET 调用)。我从未尝试过它们中的任何一个,但我会从NirCmd(NirSoft 具有类似 SysInternals 的质量工具)开始。
Unfortunately NirCmd can't parseshortcut files (only create them), but for that purpose TZWorks lpseems capable. It can even format its output as csv. lnk-parserlooks good too (it can output both HTML and CSV).
不幸的是 NirCmd 不能解析快捷方式文件(只能创建它们),但为此TZWorks lp似乎能够。它甚至可以将其输出格式化为 csv。lnk-parser看起来也不错(它可以输出 HTML 和 CSV)。
回答by Steven Jeuris
Similar to IllidanS4's answer, using the Windows Script Hostproved the be the easiest solution for me (tested on Windows 8 64 bit).
与IllidanS4 的回答类似,使用Windows Script Host被证明是最简单的解决方案(在 Windows 8 64 位上测试)。
However, rather than importing the COM type manually through code, it is easier to just add the COM type library as a reference. Choose References->Add Reference...
, COM->Type Libraries
and find and add "Windows Script Host Object Model".
但是,与通过代码手动导入 COM 类型相比,添加 COM 类型库作为引用更容易。选择References->Add Reference...
,COM->Type Libraries
然后找到并添加“Windows Script Host Object Model”。
This imports the namespace IWshRuntimeLibrary
, from which you can access:
这将导入 namespace IWshRuntimeLibrary
,您可以从中访问:
WshShell shell = new WshShell();
IWshShortcut link = (IWshShortcut)shell.CreateShortcut(LinkPathName);
link.TargetPath=TargetPathName;
link.Save();