ShortcutTool.cs 2.1 KB

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