之前,创建快捷方式使用的是WshShell,后来发现这种方法如果路径中有中文的话是不支持的。应该用Shell对象。
···
public static void CreateShortcutShell32(string ShortcutName, string targetPath, string shortcutPath, string iconLocation = null, string description = "", string arguments = "")
{
if (!Directory.Exists(shortcutPath))
{
Directory.CreateDirectory(shortcutPath);
}
string shortcutFullPath = Path.Combine(shortcutPath, $"{ShortcutName}.lnk");
// Create empty .lnk file
System.IO.File.WriteAllBytes(shortcutFullPath, new byte[0]);
// Create a ShellLinkObject that references the .lnk file
//Shell32.Shell shell = new Shell32.Shell(); // This doesn't work on Win10
Shell32.Folder dir = GetShell32Folder(shortcutPath);
Shell32.FolderItem item = dir.Items().Item($"{ShortcutName}.lnk");
Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)item.GetLink;
// Set the .lnk file properties
lnk.Path = targetPath;
lnk.Description = description;
lnk.Arguments = arguments;
lnk.WorkingDirectory = Path.GetDirectoryName(targetPath);
lnk.SetIconLocation(string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation, 0);
lnk.Save(shortcutFullPath);
}
···
注意 Shell32.Shell shell = new Shell32.Shell(); 的方式在Win10上不能用,需要用反射的方式来获取Shell32.Folder对象
private static Shell32.Folder GetShell32Folder(string folderPath)
{
Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
Object shell = Activator.CreateInstance(shellAppType);
return (Shell32.Folder)shellAppType.InvokeMember("NameSpace",
System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { folderPath });
}
同时,因为不能直接创建lnk,所以先创建一个空白的,然后修改各项属性。
参考:
https://stackoverflow.com/a/19035049/5793480
网友评论