デスクトップにショートカットを作成する


106

.NET Framework 3.5を使用し、公式のWindows APIに依存して、デスクトップ上にいくつかのEXEファイルを指すショートカットを作成したいと思います。どうやってやるの?


1
Rustam IrzaevのWindowsスクリプトホストオブジェクトモデルを使用することが、適切なショートカットを作成するための唯一の信頼できる方法です。ayush:この手法では、ホットキーや説明などの機能の多くが欠けています。Thorarin:ほとんどの場合、ShellLinkは適切に機能しますが、Windows XPでは機能せず、無効なショートカットが作成されます。Simon Mourier:これは非常に有望でしたが、Windows 8で無効なショートカットが作成されます
BrutalDev 2013年

Simon Mourierからの答えがここでの最良の答えです。ショートカットを作成するための正しい、弾丸を証明する唯一の方法は、オペレーティングシステムが使用するのと同じAPIを使用することです。これはIShellLinkインターフェイスです。Windowsスクリプトホストを使用したり、Webリンクを作成したりしないでください。Simon Mourierは、6行のコードでこれを行う方法を示しています。このメソッドで問題が発生した人は、必ず無効なパスを渡しました。私は彼のコードをWindows XP、7、10でテストしました。ProgramFilesなどに異なるフォルダーを使用する32/64ビットWindowsの問題を回避するために、「Any CPU」としてアプリをコンパイルしてください。
Elmue

回答:


120

ホットキー、説明などの追加オプションを使用

まず、プロジェクト>参照の追加> COM > Windowsスクリプトホストオブジェクトモデル。

using IWshRuntimeLibrary;

private void CreateShortcut()
{
  object shDesktop = (object)"Desktop";
  WshShell shell = new WshShell();
  string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\Notepad.lnk";
  IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
  shortcut.Description = "New shortcut for a Notepad";
  shortcut.Hotkey = "Ctrl+Shift+N";
  shortcut.TargetPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\notepad.exe";
  shortcut.Save();
}

2
これは本当に私に近かった。ショートカットの "WorkingDirectory"プロパティに.exeのディレクトリを追加する必要がありました。(shortcut.WorkingDirectory)+1
サミュレスク2014年

4
(IconLocationで)アイコンインデックスを指定するには、「path_to_icon_file、#」のような値を使用します。ここで、#はアイコンインデックスです。msdn.microsoft.com/en-us/library/xsy6k3ys(v=vs.84).aspxを
Chris

1
引数の場合:shortcut.Arguments = "Seta Map mp_crash"; stackoverflow.com/a/18491229/2155778
ゾルファガリ2017

7
Environment.SpecialFolders.System-存在しません... Environment.SpecialFolder.System-動作します。
JSWulf 2017年

また、Microsoft.CSharpを参照として追加する必要がある場合もあります。
l1nuxuser 2018

76

URLショートカット

private void urlShortcutToDesktop(string linkName, string linkUrl)
{
    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

    using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
    {
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=" + linkUrl);
    }
}

アプリケーションのショートカット

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

このも確認してください。

一部のAPI固有の関数を使用する場合はIShellLink interfaceIPersistFile interface(COM相互運用機能を介して)だけでなくも使用する必要があります。

ここでは、サンプルコードだけでなく、実行する必要があることについて詳しく説明した記事を示します。


上記は正常に動作しています。しかし、DllImport( "coredll.dll")]のようないくつかのAPI関数を介してショートカットを作成したいと思います。public static extern int SHCreateShortcut(StringBuilder szShortcut、StringBuilder szTarget);
Vipinアローラ

@Vipinなんで?上記の解決策のいずれかが十分ではない理由はありますか?
アレックス

8
nitpicking:Usingブロックの終了で処理する必要があるため、flush()行を削除できます
Newtopian

3
私はこの方法で多くの問題を抱えていました... Windowsはショートカット定義をどこかにキャッシュする傾向があります...このようなショートカットを作成し、それを削除してから、同じ名前でURLが異なるものを作成します...可能性はウィンドウですショートカットをクリックすると、古い削除済みURLが開きます。Rustamの以下の回答(.urlではなく.lnkを使用)はこの問題を解決しました
TCC

1
素晴らしい答え。.lnkファイルを使用するときに対処しなければならない恐ろしいCOM配管よりもはるかに優れています。
James Ko

61

以下は、外部COMオブジェクト(WSH)に依存せず、32ビットおよび64ビットプログラムをサポートするコードの一部です。

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;

namespace TestShortcut
{
    class Program
    {
        static void Main(string[] args)
        {
            IShellLink link = (IShellLink)new ShellLink();

            // setup shortcut information
            link.SetDescription("My Description");
            link.SetPath(@"c:\MyPath\MyProgram.exe");

            // save it
            IPersistFile file = (IPersistFile)link;
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            file.Save(Path.Combine(desktopPath, "MyLink.lnk"), false);
        }
    }

    [ComImport]
    [Guid("00021401-0000-0000-C000-000000000046")]
    internal class ShellLink
    {
    }

    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("000214F9-0000-0000-C000-000000000046")]
    internal interface IShellLink
    {
        void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out IntPtr pfd, int fFlags);
        void GetIDList(out IntPtr ppidl);
        void SetIDList(IntPtr pidl);
        void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
        void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
        void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
        void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
        void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
        void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
        void GetHotkey(out short pwHotkey);
        void SetHotkey(short wHotkey);
        void GetShowCmd(out int piShowCmd);
        void SetShowCmd(int iShowCmd);
        void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon);
        void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
        void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
        void Resolve(IntPtr hwnd, int fFlags);
        void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
    }
}

@BrutalDev-何が機能しないのですか?私はWindows 8 x64でテストしましたが、動作します。
Simon Mourier 2013年

また、Win8 x64を実行し、上記のコードサンプルをそのままコピーしました。これにより、デスクトップ上にパスのないアイコンが作成されます。リンクを実行すると、エクスプローラがデスクトップに開きます。これは、ShellLink.csで同様の問題でしたが、Windows XP / 2003で発生しました。「これは非常に有望たが、Windows 8に無効なショートカットを作成します」:決定的にすべてのWindowsバージョン間でのみ動作例では、私がメインの質問に私のコメントで述べたようにルスタムIrzaevの使用WSHOMだった
BrutalDevを

これはWindows 8.1 x64で動作するようになりましたが、ここで指定したコードには、現在IPersistFileの定義がありません。それを動作させるには、ShellLink.csの投稿からコピーする必要がありました。
Walter Wilfinger 14

これが機能しない具体的な理由はわかりません。とにかく、IPersistFileはそのままSystem.Runtime.InteropServices.ComTypesで利用できます
Simon Mourier 14

1
このソリューションはSetIconLocation、32ビットの実行可能ファイルを備えた64ビットのWindows 10で使用する正しいアイコンを設定しません。解決策はここで説明されています:stackoverflow.com/a/39282861と私はまた、他のすべての人が参照しているWindows 8と同じ問題であると私は思っています。64ビットWindows上の32ビットexeファイルに関連している可能性があります。
マリスB.

26

このShellLink.csクラスを使用して、ショートカットを作成できます。

デスクトップディレクトリを取得するには、次を使用します。

var dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

またはを使用Environment.SpecialFolder.CommonDesktopDirectoryして、すべてのユーザー用に作成します。


6
@Vipin:ソリューションが機能する場合は、通常、賛成票を投じます。また、最適なソリューションを選択し、それを問題の解答として受け入れる必要があります。
ソラリン

これにより、既存のexeがlnkファイルで上書きされます。Win10でテスト済み。
zwcloud

@zwcloudこのコードは何もしないため、何も上書きしません。ショートカットを操作するために使用するクラスとメソッドを通知するだけです。あなたのコードがあなたにあるexeを上書きしている場合。実際にlnkファイルを作成する方法を調べて、exeを破壊する理由を確認します。
Cdaragorn

15

追加の参照なし:

using System;
using System.Runtime.InteropServices;

public class Shortcut
{

private static Type m_type = Type.GetTypeFromProgID("WScript.Shell");
private static object m_shell = Activator.CreateInstance(m_type);

[ComImport, TypeLibType((short)0x1040), Guid("F935DC23-1CF0-11D0-ADB9-00C04FD58A0B")]
private interface IWshShortcut
{
    [DispId(0)]
    string FullName { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0)] get; }
    [DispId(0x3e8)]
    string Arguments { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3e8)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3e8)] set; }
    [DispId(0x3e9)]
    string Description { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3e9)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3e9)] set; }
    [DispId(0x3ea)]
    string Hotkey { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ea)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ea)] set; }
    [DispId(0x3eb)]
    string IconLocation { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3eb)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3eb)] set; }
    [DispId(0x3ec)]
    string RelativePath { [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ec)] set; }
    [DispId(0x3ed)]
    string TargetPath { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ed)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ed)] set; }
    [DispId(0x3ee)]
    int WindowStyle { [DispId(0x3ee)] get; [param: In] [DispId(0x3ee)] set; }
    [DispId(0x3ef)]
    string WorkingDirectory { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ef)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ef)] set; }
    [TypeLibFunc((short)0x40), DispId(0x7d0)]
    void Load([In, MarshalAs(UnmanagedType.BStr)] string PathLink);
    [DispId(0x7d1)]
    void Save();
}

public static void Create(string fileName, string targetPath, string arguments, string workingDirectory, string description, string hotkey, string iconPath)
{
    IWshShortcut shortcut = (IWshShortcut)m_type.InvokeMember("CreateShortcut", System.Reflection.BindingFlags.InvokeMethod, null, m_shell, new object[] { fileName });
    shortcut.Description = description;
    shortcut.Hotkey = hotkey;
    shortcut.TargetPath = targetPath;
    shortcut.WorkingDirectory = workingDirectory;
    shortcut.Arguments = arguments;
    if (!string.IsNullOrEmpty(iconPath))
        shortcut.IconLocation = iconPath;
    shortcut.Save();
}
}

デスクトップにショートカットを作成するには:

    string lnkFileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Notepad.lnk");
    Shortcut.Create(lnkFileName,
        System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "notepad.exe"),
        null, null, "Open Notepad", "Ctrl+Shift+N", null);

11

私は自分のアプリで単に使用します:

using IWshRuntimeLibrary; // > Ref > COM > Windows Script Host Object  
...   
private static void CreateShortcut()
    {
        string link = Environment.GetFolderPath( Environment.SpecialFolder.Desktop ) 
            + Path.DirectorySeparatorChar + Application.ProductName + ".lnk";
        var shell = new WshShell();
        var shortcut = shell.CreateShortcut( link ) as IWshShortcut;
        shortcut.TargetPath = Application.ExecutablePath;
        shortcut.WorkingDirectory = Application.StartupPath;
        //shortcut...
        shortcut.Save();
    }

そのまま使用できます。コピーして貼り付けてください
rluks

9

使用ShellLink.csを簡単にショートカットを作成するvbAcceleratorで!

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

3
そのリンクは死んでいますが、アーカイブされたバージョンはここにあります
pswg

7

これが私のコードです:

public static class ShortcutHelper
{
    #region Constants
    /// <summary>
    /// Default shortcut extension
    /// </summary>
    public const string DEFAULT_SHORTCUT_EXTENSION = ".lnk";

    private const string WSCRIPT_SHELL_NAME = "WScript.Shell";
    #endregion

    /// <summary>
    /// Create shortcut in current path.
    /// </summary>
    /// <param name="linkFileName">shortcut name(include .lnk extension.)</param>
    /// <param name="targetPath">target path</param>
    /// <param name="workingDirectory">working path</param>
    /// <param name="arguments">arguments</param>
    /// <param name="hotkey">hot key(ex: Ctrl+Shift+Alt+A)</param>
    /// <param name="shortcutWindowStyle">window style</param>
    /// <param name="description">shortcut description</param>
    /// <param name="iconNumber">icon index(start of 0)</param>
    /// <returns>shortcut file path.</returns>
    /// <exception cref="System.IO.FileNotFoundException"></exception>
    public static string CreateShortcut(
        string linkFileName,
        string targetPath,
        string workingDirectory = "",
        string arguments = "",
        string hotkey = "",
        ShortcutWindowStyles shortcutWindowStyle = ShortcutWindowStyles.WshNormalFocus,
        string description = "",
        int iconNumber = 0)
    {
        if (linkFileName.Contains(DEFAULT_SHORTCUT_EXTENSION) == false)
        {
            linkFileName = string.Format("{0}{1}", linkFileName, DEFAULT_SHORTCUT_EXTENSION);
        }

        if (File.Exists(targetPath) == false)
        {
            throw new FileNotFoundException(targetPath);
        }

        if (workingDirectory == string.Empty)
        {
            workingDirectory = Path.GetDirectoryName(targetPath);
        }

        string iconLocation = string.Format("{0},{1}", targetPath, iconNumber);

        if (Environment.Version.Major >= 4)
        {
            Type shellType = Type.GetTypeFromProgID(WSCRIPT_SHELL_NAME);
            dynamic shell = Activator.CreateInstance(shellType);
            dynamic shortcut = shell.CreateShortcut(linkFileName);

            shortcut.TargetPath = targetPath;
            shortcut.WorkingDirectory = workingDirectory;
            shortcut.Arguments = arguments;
            shortcut.Hotkey = hotkey;
            shortcut.WindowStyle = shortcutWindowStyle;
            shortcut.Description = description;
            shortcut.IconLocation = iconLocation;

            shortcut.Save();
        }
        else
        {
            Type shellType = Type.GetTypeFromProgID(WSCRIPT_SHELL_NAME);
            object shell = Activator.CreateInstance(shellType);
            object shortcut = shellType.InvokeMethod("CreateShortcut", shell, linkFileName);
            Type shortcutType = shortcut.GetType();

            shortcutType.InvokeSetMember("TargetPath", shortcut, targetPath);
            shortcutType.InvokeSetMember("WorkingDirectory", shortcut, workingDirectory);
            shortcutType.InvokeSetMember("Arguments", shortcut, arguments);
            shortcutType.InvokeSetMember("Hotkey", shortcut, hotkey);
            shortcutType.InvokeSetMember("WindowStyle", shortcut, shortcutWindowStyle);
            shortcutType.InvokeSetMember("Description", shortcut, description);
            shortcutType.InvokeSetMember("IconLocation", shortcut, iconLocation);

            shortcutType.InvokeMethod("Save", shortcut);
        }

        return Path.Combine(System.Windows.Forms.Application.StartupPath, linkFileName);
    }

    private static object InvokeSetMember(this Type type, string methodName, object targetInstance, params object[] arguments)
    {
        return type.InvokeMember(
            methodName,
            BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty,
            null,
            targetInstance,
            arguments);
    }

    private static object InvokeMethod(this Type type, string methodName, object targetInstance, params object[] arguments)
    {
        return type.InvokeMember(
            methodName,
            BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
            null,
            targetInstance,
            arguments);
    }

    /// <summary>
    /// windows styles
    /// </summary>
    public enum ShortcutWindowStyles
    {
        /// <summary>
        /// Hide
        /// </summary>
        WshHide = 0,
        /// <summary>
        /// NormalFocus
        /// </summary>
        WshNormalFocus = 1,
        /// <summary>
        /// MinimizedFocus
        /// </summary>
        WshMinimizedFocus = 2,
        /// <summary>
        /// MaximizedFocus
        /// </summary>
        WshMaximizedFocus = 3,
        /// <summary>
        /// NormalNoFocus
        /// </summary>
        WshNormalNoFocus = 4,
        /// <summary>
        /// MinimizedNoFocus
        /// </summary>
        WshMinimizedNoFocus = 6,
    }
}

5

編集:私はこのソリューションをもうお勧めしません。それでもWindowsスクリプトエンジンを使用するより良い方法がない場合は、少なくともメモリにプレーンテキストスクリプトを作成するのではなく、エンジンを直接呼び出す@Mehmetのソリューションを使用してください。

VBScriptを使用してショートカットを生成しました。p / Invoke、COM Interop、および追加のDLLは必要ありません。それはこのように動作します:

  • CreateShortcut C#メソッドの指定されたパラメーターを使用して、実行時にVBScriptを生成します。
  • このVBScriptを一時ファイルに保存します
  • スクリプトが完了するまで待ちます
  • 一時ファイルを削除する

どうぞ:

static string _scriptTempFilename;

/// <summary>
/// Creates a shortcut at the specified path with the given target and
/// arguments.
/// </summary>
/// <param name="path">The path where the shortcut will be created. This should
///     be a file with the LNK extension.</param>
/// <param name="target">The target of the shortcut, e.g. the program or file
///     or folder which will be opened.</param>
/// <param name="arguments">The additional command line arguments passed to the
///     target.</param>
public static void CreateShortcut(string path, string target, string arguments)
{
    // Check if link path ends with LNK or URL
    string extension = Path.GetExtension(path).ToUpper();
    if (extension != ".LNK" && extension != ".URL")
    {
        throw new ArgumentException("The path of the shortcut must have the extension .lnk or .url.");
    }

    // Get temporary file name with correct extension
    _scriptTempFilename = Path.GetTempFileName();
    File.Move(_scriptTempFilename, _scriptTempFilename += ".vbs");

    // Generate script and write it in the temporary file
    File.WriteAllText(_scriptTempFilename, String.Format(@"Dim WSHShell
Set WSHShell = WScript.CreateObject({0}WScript.Shell{0})
Dim Shortcut
Set Shortcut = WSHShell.CreateShortcut({0}{1}{0})
Shortcut.TargetPath = {0}{2}{0}
Shortcut.WorkingDirectory = {0}{3}{0}
Shortcut.Arguments = {0}{4}{0}
Shortcut.Save",
        "\"", path, target, Path.GetDirectoryName(target), arguments),
        Encoding.Unicode);

    // Run the script and delete it after it has finished
    Process process = new Process();
    process.StartInfo.FileName = _scriptTempFilename;
    process.Start();
    process.WaitForExit();
    File.Delete(_scriptTempFilename);
}

3

(テスト済みの)拡張メソッドを以下に示します。

using IWshRuntimeLibrary;
using System;

namespace Extensions
{
    public static class XShortCut
    {
        /// <summary>
        /// Creates a shortcut in the startup folder from a exe as found in the current directory.
        /// </summary>
        /// <param name="exeName">The exe name e.g. test.exe as found in the current directory</param>
        /// <param name="startIn">The shortcut's "Start In" folder</param>
        /// <param name="description">The shortcut's description</param>
        /// <returns>The folder path where created</returns>
        public static string CreateShortCutInStartUpFolder(string exeName, string startIn, string description)
        {
            var startupFolderPath = Environment.SpecialFolder.Startup.GetFolderPath();
            var linkPath = startupFolderPath + @"\" + exeName + "-Shortcut.lnk";
            var targetPath = Environment.CurrentDirectory + @"\" + exeName;
            XFile.Delete(linkPath);
            Create(linkPath, targetPath, startIn, description);
            return startupFolderPath;
        }

        /// <summary>
        /// Create a shortcut
        /// </summary>
        /// <param name="fullPathToLink">the full path to the shortcut to be created</param>
        /// <param name="fullPathToTargetExe">the full path to the exe to 'really execute'</param>
        /// <param name="startIn">Start in this folder</param>
        /// <param name="description">Description for the link</param>
        public static void Create(string fullPathToLink, string fullPathToTargetExe, string startIn, string description)
        {
            var shell = new WshShell();
            var link = (IWshShortcut)shell.CreateShortcut(fullPathToLink);
            link.IconLocation = fullPathToTargetExe;
            link.TargetPath = fullPathToTargetExe;
            link.Description = description;
            link.WorkingDirectory = startIn;
            link.Save();
        }
    }
}

そして使用例:

XShortCut.CreateShortCutInStartUpFolder(THEEXENAME, 
    Environment.CurrentDirectory,
    "Starts some executable in the current directory of application");

1番目のパラメーターは、exe名を設定します(現在のディレクトリにあります)2番目のパラメーターは「開始」フォルダーで、3番目のパラメーターはショートカットの説明です。

このコードの使用例

リンクの命名規則により、リンクの動作が明確になります。リンクをテストするには、リンクをダブルクリックします。

最後の注意:アプリケーション自体(ターゲット)には、ICONイメージが関連付けられている必要があります。リンクは、exe内でアイコンを簡単に見つけることができます。ターゲットアプリケーションに複数のアイコンがある場合は、リンクのプロパティを開き、アイコンをexeで見つかった他のアイコンに変更できます。


.GetFolderPath()が存在しないというエラーメッセージが表示されます。XFile.Deleteについても同様です。何が欠けていますか?
RalphF 2017

ここでエラーが発生しますか?Environment.SpecialFolder.Startup.GetFolderPath();
ジョンピーターズ

2

「Windowsスクリプトホストオブジェクトモデル」リファレンスを使用してショートカットを作成します。

プロジェクト参照への「Windowsスクリプトホストオブジェクトモデル」の追加

特定の場所にショートカットを作成するには:

    void CreateShortcut(string linkPath, string filename)
    {
        // Create shortcut dir if not exists
        if (!Directory.Exists(linkPath))
            Directory.CreateDirectory(linkPath);

        // shortcut file name
        string linkName = Path.ChangeExtension(Path.GetFileName(filename), ".lnk");

        // COM object instance/props
        IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
        IWshRuntimeLibrary.IWshShortcut sc = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(linkName);
        sc.Description = "some desc";
        //shortcut.IconLocation = @"C:\..."; 
        sc.TargetPath = linkPath;
        // save shortcut to target
        sc.Save();
    }

0
private void CreateShortcut(string executablePath, string name)
    {
        CMDexec("echo Set oWS = WScript.CreateObject('WScript.Shell') > CreateShortcut.vbs");
        CMDexec("echo sLinkFile = '" + Environment.GetEnvironmentVariable("homedrive") + "\\users\\" + Environment.GetEnvironmentVariable("username") + "\\desktop\\" + name + ".ink' >> CreateShortcut.vbs");
        CMDexec("echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs");
        CMDexec("echo oLink.TargetPath = '" + executablePath + "' >> CreateShortcut.vbs");
        CMDexec("echo oLink.Save >> CreateShortcut.vbs");
        CMDexec("cscript CreateShortcut.vbs");
        CMDexec("del CreateShortcut.vbs");
    }

0

Rustam Irzaevの回答に基づいて、IWshRuntimeLibraryを使用してラッパークラスを作成しました。

IWshRuntimeLibrary->参照-> COM> Windowsスクリプトホストオブジェクトモデル

using System;
using System.IO;
using IWshRuntimeLibrary;
using File = System.IO.File;

public static class Shortcut
{
    public static void CreateShortcut(string originalFilePathAndName, string destinationSavePath)
    {
        string fileName = Path.GetFileNameWithoutExtension(originalFilePathAndName);
        string originalFilePath = Path.GetDirectoryName(originalFilePathAndName);

        string link = destinationSavePath + Path.DirectorySeparatorChar + fileName + ".lnk";
        var shell = new WshShell();
        var shortcut = shell.CreateShortcut(link) as IWshShortcut;
        if (shortcut != null)
        {
            shortcut.TargetPath = originalFilePathAndName;
            shortcut.WorkingDirectory = originalFilePath;
            shortcut.Save();
        }
    }

    public static void CreateStartupShortcut()
    {
        CreateShortcut(System.Reflection.Assembly.GetEntryAssembly()?.Location, Environment.GetFolderPath(Environment.SpecialFolder.Startup));
    }

    public static void DeleteShortcut(string originalFilePathAndName, string destinationSavePath)
    {
        string fileName = Path.GetFileNameWithoutExtension(originalFilePathAndName);
        string originalFilePath = Path.GetDirectoryName(originalFilePathAndName);

        string link = destinationSavePath + Path.DirectorySeparatorChar + fileName + ".lnk";
        if (File.Exists(link)) File.Delete(link);
    }

    public static void DeleteStartupShortcut()
    {
        DeleteShortcut(System.Reflection.Assembly.GetEntryAssembly()?.Location, Environment.GetFolderPath(Environment.SpecialFolder.Startup));
    }
}

-2

Windows Vista / 7/8/10の場合、代わりにを介してシンボリックリンクを作成できますmklink

Process.Start("cmd.exe", $"/c mklink {linkName} {applicationPath}");

または、CreateSymbolicLinkP / Invoke経由で呼び出します。


これはショートカットとは関係ありません。
マット
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.