Создание ярлыка приложения в каталоге - PullRequest
70 голосов
/ 24 октября 2008

Как создать ярлык приложения (файл .lnk) в C # или с помощью .NET Framework?

Результатом будет файл .lnk для указанного приложения или URL.

Ответы [ 6 ]

61 голосов
/ 24 октября 2008

Это не так просто, как мне бы хотелось, но есть классный вызов класса ShellLink.cs в vbAccelerator

Этот код использует взаимодействие, но не использует WSH.

Используя этот класс, код для создания ярлыка:

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);
    }
}
49 голосов
/ 11 ноября 2013

Красиво и чисто. ( .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);
}

Вот и все, дополнительный код не требуется. CreateShortcut может даже загружать ярлык из файла, поэтому такие свойства как TargetPath возвращают существующую информацию Свойства объекта ярлыка .

Это также возможно для версий .NET, не поддерживающих динамические типы. ( .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);
}
14 голосов
/ 29 апреля 2010

Я нашел что-то вроде этого:

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();
    }
}

Оригинальный код на Статья печалиста "url-link-to-desktop"

1 голос
/ 09 февраля 2015

Аналогично ответу IllidanS4 , с использованием Windows Script Host оказался для меня самым простым решением (проверено на 64-битной Windows 8).

Однако, вместо того, чтобы импортировать тип COM вручную через код, проще просто добавить библиотеку типов COM в качестве ссылки. Выберите References->Add Reference..., COM->Type Libraries, найдите и добавьте «Объектная модель хоста сценариев Windows» .

Импортирует пространство имен IWshRuntimeLibrary, из которого вы можете получить доступ:

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

Кредит достается Джиму Холленхорсту .

1 голос
/ 24 мая 2014

После изучения всех возможностей, которые я нашел на SO, я остановился на 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;
    ...
}

Помимо простоты и эффективности, автор (Mattias Sjögren, MS MVP) является своего рода гуру COM / PInvoke / Interop, и я считаю, что его код более надежный, чем альтернативы.

Следует отметить, что файлы ярлыков также могут быть созданы несколькими утилитами командной строки (которые, в свою очередь, могут быть легко вызваны из C # /. NET). Я никогда не пробовал ни одного из них, но я бы начал с NirCmd (у NirSoft есть качественные инструменты, подобные SysInternals).

К сожалению, NirCmd не может анализировать файлы ярлыков (только создавать их), но для этой цели TZWorks lp кажется способным. Он может даже отформатировать свой вывод как CSV. lnk-parser тоже хорошо выглядит (он может выводить как HTML, так и CSV).

1 голос
/ 20 декабря 2013

Загрузка IWshRuntimeLibrary

Вам также необходимо импортировать библиотеку COM IWshRuntimeLibrary. Щелкните правой кнопкой мыши свой проект -> добавить ссылку -> COM -> IWshRuntimeLibrary -> добавить, а затем используйте следующий фрагмент кода.

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();

}
...