使用 C# 代码读取或创建快捷方式。
1 基本 Code
/// <summary>/// 创建一个快捷方式/// </summary>/// <param name="lnkFilePath">快捷方式的完全限定路径。</param>/// <param name="workDir"></param>/// <param name="args">快捷方式启动程序时需要使用的参数。</param>/// <param name="targetPath"></param>public static void CreateShortcut(string lnkFilePath, string targetPath, string workDir, string args = ""){ var shellType = Type.GetTypeFromProgID("WScript.Shell"); dynamic shell = Activator.CreateInstance(shellType); var shortcut = shell.CreateShortcut(lnkFilePath); shortcut.TargetPath = targetPath; shortcut.Arguments = args; shortcut.WorkingDirectory = workDir; shortcut.Save();}
/// <summary>/// 读取一个快捷方式的信息/// </summary>/// <param name="lnkFilePath"></param>/// <returns></returns>public static ShortcutDescription ReadShortcut(string lnkFilePath){ var shellType = Type.GetTypeFromProgID("WScript.Shell"); dynamic shell = Activator.CreateInstance(shellType); var shortcut = shell.CreateShortcut(lnkFilePath); return new ShortcutDescription() { TargetPath = shortcut.TargetPath, Arguments = shortcut.Arguments, WorkDir = shortcut.WorkingDirectory, };}
以上只列出了 TargetPath
,Arguments
,WorkingDirectory
这几个属性的读写,其它属性类似。
2 相关参考
用C#创建应用程序桌面快捷方式_luwq168的专栏-CSDN博客
c# - Create a shortcut on Desktop - Stack Overflow
这里的例子比较多:
WshShell.CreateShortcut C# (CSharp) Code Examples - HotExamples
3 注意事项
处理桌面上的快捷方式时,需要注意桌面文件夹的位置,用户自定义位置之后,快捷方式的位置可能有变化。
桌面上两个快捷方式,不一定在同一个目录下:
System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
拿到的是用户定义过的桌面,
System.Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory)
可以拿到 public 公共桌面。
原文链接: https://blog.jgrass.cc/posts/csharp-shortcut/
本作品采用 「署名 4.0 国际」 许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。