visual studio instalador form ejecutable datos crear como c# .net file-io shortcut

c# - studio - Crear acceso directo a aplicaciones en un directorio



crear instalador visual studio 2017 (6)

¿Cómo se crea un acceso directo a la aplicación (archivo .lnk) en C # o usando .NET Framework?

El resultado sería un archivo .lnk a la aplicación o URL especificada.


Bonito y limpio. ( .NET 4.0 )

Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object dynamic shell = Activator.CreateInstance(t); try{ var lnk = shell.CreateShortcut("sc.lnk"); try{ lnk.TargetPath = @"C:/something"; lnk.IconLocation = "shell32.dll, 1"; lnk.Save(); }finally{ Marshal.FinalReleaseComObject(lnk); } }finally{ Marshal.FinalReleaseComObject(shell); }

Eso es todo, no se necesita código adicional. CreateShortcut incluso puede cargar acceso directo desde el archivo, por lo que propiedades como TargetPath devuelven información existente. Propiedades del objeto de acceso directo .

También es posible de esta manera para las versiones de .NET que no admiten tipos dinámicos. ( .NET 3.5 )

Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object object shell = Activator.CreateInstance(t); try{ object lnk = t.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell, new object[]{"sc.lnk"}); try{ t.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk, new object[]{@"C:/whatever"}); t.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk, new object[]{"shell32.dll, 5"}); t.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null); }finally{ Marshal.FinalReleaseComObject(lnk); } }finally{ Marshal.FinalReleaseComObject(shell); }


Después de estudiar todas las posibilidades que encontré en SO, me he decidido por ShellLink :

//Create new shortcut using (var shellShortcut = new ShellShortcut(newShortcutPath) { Path = path WorkingDirectory = workingDir, Arguments = args, IconPath = iconPath, IconIndex = iconIndex, Description = description, }) { shellShortcut.Save(); } //Read existing shortcut using (var shellShortcut = new ShellShortcut(existingShortcut)) { path = shellShortcut.Path; args = shellShortcut.Arguments; workingDir = shellShortcut.WorkingDirectory; ... }

Además de ser simple y efectivo, el autor (Mattias Sjögren, MS MVP) es una especie de gurú COM / PInvoke / Interop, y al leer su código creo que es más sólido que las alternativas.

Cabe mencionar que los archivos de acceso directo también pueden ser creados por varias utilidades de línea de comandos (que a su vez pueden invocarse fácilmente desde C # / .NET). Nunca intenté con ninguno de ellos, pero empezaría con NirCmd (NirSoft tiene herramientas de calidad similares a SysInternals).

Lamentablemente, NirCmd no puede analizar los archivos de acceso directo (solo crearlos), pero para ese fin, TZWorks lp parece capaz. Incluso puede formatear su salida como csv. lnk-parser ve bien (puede generar tanto HTML como CSV).


Encontré algo como esto:

private void appShortcutToDesktop(string linkName) { string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); using (StreamWriter writer = new StreamWriter(deskDir + "//" + linkName + ".url")) { string app = System.Reflection.Assembly.GetExecutingAssembly().Location; writer.WriteLine("[InternetShortcut]"); writer.WriteLine("URL=file:///" + app); writer.WriteLine("IconIndex=0"); string icon = app.Replace(''//', ''/''); writer.WriteLine("IconFile=" + icon); writer.Flush(); } }

Código original en el artículo de sorrowman "url-link-to-desktop"


No es tan simple como me hubiera gustado, pero hay una gran clase llamada ShellLink.cs en vbAccelerator

Este código usa interoperabilidad, pero no depende de WSH.

Usando esta clase, el código para crear el atajo es:

private static void configStep_addShortcutToStartupGroup() { using (ShellLink shortcut = new ShellLink()) { shortcut.Target = Application.ExecutablePath; shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath); shortcut.Description = "My Shorcut Name Here"; shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; shortcut.Save(STARTUP_SHORTCUT_FILEPATH); } }


Similar a la respuesta de IllidanS4 , el uso del Windows Script Host resultó ser la solución más fácil para mí (probada en Windows 8 de 64 bits).

Sin embargo, en lugar de importar el tipo COM manualmente a través del código, es más fácil simplemente agregar la biblioteca de tipo COM como referencia. Elija References->Add Reference... , COM->Type Libraries y busque y agregue "Windows Script Host Object Model" .

Esto importa el espacio de nombres IWshRuntimeLibrary , desde el que puede acceder a:

WshShell shell = new WshShell(); IWshShortcut link = (IWshShortcut)shell.CreateShortcut(LinkPathName); link.TargetPath=TargetPathName; link.Save();

codeproject.com/Articles/3905/… .


Descargue IWshRuntimeLibrary

También necesita importar la biblioteca COM IWshRuntimeLibrary . Haga clic derecho en su proyecto -> agregar referencia -> COM -> IWshRuntimeLibrary -> agregar y luego use el siguiente fragmento de código.

private void createShortcutOnDesktop(String executablePath) { // Create a new instance of WshShellClass WshShell lib = new WshShellClass(); // Create the shortcut IWshRuntimeLibrary.IWshShortcut MyShortcut; // Choose the path for the shortcut string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); MyShortcut = (IWshRuntimeLibrary.IWshShortcut)lib.CreateShortcut(@deskDir+"//AZ.lnk"); // Where the shortcut should point to //MyShortcut.TargetPath = Application.ExecutablePath; MyShortcut.TargetPath = @executablePath; // Description for the shortcut MyShortcut.Description = "Launch AZ Client"; StreamWriter writer = new StreamWriter(@"D:/AZ/logo.ico"); Properties.Resources.system.Save(writer.BaseStream); writer.Flush(); writer.Close(); // Location for the shortcut''s icon MyShortcut.IconLocation = @"D:/AZ/logo.ico"; // Create the shortcut at the given path MyShortcut.Save(); }