C#自动建立快捷方式

2021年11月26日 阅读数:12
这篇文章主要向大家介绍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();
    }
}