ShortcutTool.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //############################################################
  2. // https://github.com/yuzhengyang
  3. // author:yuzhengyang
  4. //############################################################
  5. using Y.Utils.IOUtils.PathUtils;
  6. namespace Y.Utils.WindowsUtils.InfoUtils
  7. {
  8. public class ShortcutTool
  9. {
  10. public static bool Create(string directory, string shortcutName, string targetPath,
  11. string description = null, string iconLocation = null)
  12. {
  13. try
  14. {
  15. if (!Directory.Exists(directory))
  16. {
  17. Directory.CreateDirectory(directory);
  18. }
  19. //添加引用 Com 中搜索 Windows Script Host Object Model
  20. string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
  21. IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
  22. IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);//创建快捷方式对象
  23. shortcut.TargetPath = targetPath;//指定目标路径
  24. shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置
  25. shortcut.WindowStyle = 1;//设置运行方式,默认为常规窗口
  26. shortcut.Description = description;//设置备注
  27. shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径
  28. shortcut.Save();//保存快捷方式
  29. return true;
  30. }
  31. catch
  32. { }
  33. return false;
  34. }
  35. public static bool Delete(string directory, string shortcutName)
  36. {
  37. try
  38. {
  39. string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
  40. if (File.Exists(shortcutPath))
  41. {
  42. File.Delete(shortcutPath);
  43. }
  44. return true;
  45. }
  46. catch { }
  47. return false;
  48. }
  49. }
  50. }