15/7/14

Crear un acceso directo (Link) desde C#

(Con .net 4)
Type ShellType = Type.GetTypeFromProgID("WScript.Shell");
dynamic Shell = Activator.CreateInstance(ShellType);
dynamic shortcut = Shell.CreateShortcut(@"c:\borrame.lnk");
shortcut.TargetPath = @"c:\Windows\Notepad.exe";
shortcut.WorkingDirectory = @"c:\Windows";
shortcut.Save();
(Esto es antiguo con .net 4 usar el anterior)
Basado en:
http://www.codeproject.com/Articles/3905/Creating-Shell-Links-Shortcuts-in-NET-Programs-Usi
Por debajo usa Windows Scripting Host con lo que hay que importar un com (ocx) para que funcione. Es un poco chapuza pero es lo que hay.
En el proyecto se añade la referencia a ese com:
  1. En el proyecto,
  2. añadir referencia,
  3. de tipo com,
  4. el nombre es: “Windows Script Host Object Model”
Desde ese momento deja hacer un:
using IWshRuntimeLibrary;
El código que crea un link al notepad en el escritorio sería:

var shell = new WshShell();
IWshShortcut  link = (IWshShortcut)shell.CreateShortcut((Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"borrame.lnk")));
link.TargetPath = @"c:\windows\notepad.exe";
link.Save();

No hay comentarios: