使用 C# 建立捷徑

本篇文章示範如何使用 C# 建立捷徑

  • 透過 Visual Studio 新增 COM 參考,勾選 Windows Script Host Object Model image

  • using IWshRuntimeLibrary 後建立捷徑

    1
    2
    3
    4
    5
    6
    7
    8
      string pathLink = "C:\Users\Haoger\Desktop\test.lnk";
      string targetPath = "D:\Tests";
    
      IWshShell wshShell = new WshShellClass();
      IWshShortcut shortcut = (IWshShortcut)wshShell.CreateShortcut(pathLink);
      shortcut.TargetPath = targetPath.Replace("/", "\");
      shortcut.Description = "It is a shortcut";
      shortcut.Save();
    
    • 寫完了之後發現 compile 不會過,會出現 無法內嵌 Interop 類型 'WshShellClass'。請改用適當的介面。 的錯誤訊息,這時將 IWshRuntimeLibrary COM 參考屬性中的內嵌 Interop 類型改成「否」即可 image

      特別注意 TargetPath 必須存在且不能 / 與 \ 混和,捷徑雖然能建立,但是按了沒效果

  • 執行結果

    image

相關連結