C#自动创建快捷方式

1.NET4.0之后动态类型版本

public static void CreateShortcut(string lnkName)
{
    var startup = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
    var lnkFilePath = Path.Combine(startup, $"{lnkName}.lnk");
    if (File.Exists(lnkFilePath ))
        return;

    var shellType = Type.GetTypeFromProgID("WScript.Shell");
    dynamic shell = Activator.CreateInstance(shellType);
    var shortcut = shell.CreateShortcut(lnkFilePath);
    shortcut.TargetPath = Assembly.GetEntryAssembly().Location;
    shortcut.Arguments = "";
    shortcut.WorkingDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
    shortcut.Save();
}

2.NET3.5及之前反射版本

public static void CreateShortcut(string lnkName)
{
    var startup = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
    var lnkFilePath = Path.Combine(startup, $"{lnkName}.lnk");
    if (File.Exists(lnkFilePath ))
        return;

    var shellType = Type.GetTypeFromProgID("WScript.Shell");
    var shell = Activator.CreateInstance(shellType);
    var shortcut = shellType.InvokeMember("CreateShortcut", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, shell, new object[] { lnkFilePath });
    var shortcutType = shortcut.GetType();
    shortcutType.InvokeMember("TargetPath", BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty, null, shortcut, new object[] { Assembly.GetEntryAssembly().Location });
    shortcutType.InvokeMember("Arguments", BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty, null, shortcut, new object[] { args });
    shortcutType.InvokeMember("WorkingDirectory", BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty, null, shortcut, new object[] { AppDomain.CurrentDomain.SetupInformation.ApplicationBase });
    shortcutType.InvokeMember("Save", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, shortcut, null);
}

3.创建网页快捷方式

public static void CreateUrlShortcut(string lnkFileName, string url, string iconFile)
{
    if (File.Exists(lnkFileName))
        return;

    using (var writer = new StreamWriter(lnkFileName))
    {
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=" + url);
        writer.WriteLine("HotKey=0");
        writer.WriteLine("IconIndex=0");
        writer.WriteLine("IconFile=" + iconFile);
        writer.Flush();
    }
}
posted @ 2021-10-10 20:21  known  阅读(397)  评论(0编辑  收藏  举报