在Windows中建立快捷方式很简单,直接用右键点击文件或文件夹,选择建立快捷方式便可。若是想用C#代码的方式建立,就没有那么方便了,由于.NET框架没有提供直接建立快捷方式的方法。html
首先咱们看一下快捷方式是什么。对快捷方式点右键,选择属性菜单,在弹出的属性对话框的常规Tab中能够看到,文件类型是快捷方式(.lnk),因此快捷方式本质上是lnk文件。shell
切换到快捷方式Tab,能够看到该快捷方式的相关属性(以下图)。express
(题外话:IE的快捷方式又把我恶心到了,目标后面紧跟着360的垃圾网址。这就是运行浏览器时自动打开某个网址的一种方式,极度鄙视这种流氓行为。)浏览器
使用C#建立快捷方式就是要建立一个lnk文件,并设置相关的属性。.NET框架自己是没有提供方法的,须要引入IWshRuntimeLibrary。在添加引用对话框中搜索Windows Script Host Object Model,选择以后添加到Project的引用中。框架
详细代码以下:(文章来源:http://www.cnblogs.com/conexpress/p/ShortcutCreator.html)spa
1 using IWshRuntimeLibrary; 2 using System.IO; 3 using System; 4
5 namespace MyLibrary 6 { 7 /// <summary>
8 /// 建立快捷方式的类 9 /// </summary>
10 /// <remarks></remarks>
11 public class ShortcutCreator 12 { 13 //须要引入IWshRuntimeLibrary,搜索Windows Script Host Object Model
14
15 /// <summary>
16 /// 建立快捷方式 17 /// </summary>
18 /// <param name="directory">快捷方式所处的文件夹</param>
19 /// <param name="shortcutName">快捷方式名称</param>
20 /// <param name="targetPath">目标路径</param>
21 /// <param name="description">描述</param>
22 /// <param name="iconLocation">图标路径,格式为"可执行文件或DLL路径, 图标编号", 23 /// 例如System.Environment.SystemDirectory + "\\" + "shell32.dll, 165"</param>
24 /// <remarks></remarks>
25 public static void CreateShortcut(string directory, string shortcutName, string targetPath, 26 string description = null, string iconLocation = null) 27 { 28 if (!System.IO.Directory.Exists(directory)) 29 { 30 System.IO.Directory.CreateDirectory(directory); 31 } 32
33 string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName)); 34 WshShell shell = new WshShell(); 35 IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);//建立快捷方式对象
36 shortcut.TargetPath = targetPath;//指定目标路径
37 shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置
38 shortcut.WindowStyle = 1;//设置运行方式,默认为常规窗口
39 shortcut.Description = description;//设置备注
40 shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径
41 shortcut.Save();//保存快捷方式
42 } 43
44 /// <summary>
45 /// 建立桌面快捷方式 46 /// </summary>
47 /// <param name="shortcutName">快捷方式名称</param>
48 /// <param name="targetPath">目标路径</param>
49 /// <param name="description">描述</param>
50 /// <param name="iconLocation">图标路径,格式为"可执行文件或DLL路径, 图标编号"</param>
51 /// <remarks></remarks>
52 public static void CreateShortcutOnDesktop(string shortcutName, string targetPath, 53 string description = null, string iconLocation = null) 54 { 55 string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//获取桌面文件夹路径
56 CreateShortcut(desktop, shortcutName, targetPath, description, iconLocation); 57 } 58
59 } 60 }
若是须要获取快捷方式的属性,能够调用WshShell对象的CreateShortcut方法,传入完整的快捷方式文件路径便可获得已有快捷方式的IWshShortcut实体。修改快捷方式的属性,则修改IWshShortcut实体的属性,而后调用Save方法便可。3d