管理

快捷方式工具类 - C#小函数类推荐

Posted on 2024-11-19 13:53  lzhdim  阅读(512)  评论(0编辑  收藏  举报

       此文记录的是快捷方式操作类。

/***

    快捷方式工具类

    Austin Liu 刘恒辉
    Project Manager and Software Designer

    E-Mail: lzhdim@163.com
    Blog:   http://lzhdim.cnblogs.com
    Date:   2024-01-15 15:18:00

    使用参考:
        ShortCutUtil.CreateShortcut("D:\\LzhdimSoft\\LzhdimSoft.lnk", Application.ExecutablePath);

***/

namespace Lzhdim.LPF.Utility
{
    using System;
    using System.IO;

    /// <summary>
    /// 快捷方式工具类
    /// </summary>
    public class ShortCutUtil
    {
        /// <summary>
        /// 按指定路径创建快捷方式
        /// </summary>
        /// <param name="lnkFullPath">快捷方式绝对路径</param>
        /// <param name="appPath">应用所在路径</param>
        /// <param name="startupArgs">快捷方式启动参数</param>
        public static void CreateShortcut(string lnkFullPath, string appPath, string startupArgs = "")
        {
            var shellType = Type.GetTypeFromProgID("WScript.Shell");
            dynamic shell = Activator.CreateInstance(shellType);
            var shortcut = shell.CreateShortcut(lnkFullPath);
            var exeName = Path.GetFileName(appPath);
            var exeDir = Path.GetDirectoryName(appPath);
            // 工作目录和目标路径可以自由指定,注意TargetPath必须是exe的绝对路径
            shortcut.WorkingDirectory = exeDir;
            shortcut.TargetPath = Path.Combine(exeDir, exeName);
            shortcut.Arguments = startupArgs;
            //shortcut.iconLocation = appPath;
            shortcut.Save();
        }

        /// <summary>
        /// 根据快捷方式路径获取对应的应用路径
        /// </summary>
        /// <param name="shortcutPath">快捷方式文件路径</param>
        /// <returns>快捷方式对应的应用路径</returns>
        public static string GetTargetPathFromShortcut(string shortcutPath)
        {
            string targetPath = string.Empty;
            Type t = Type.GetTypeFromProgID("WScript.Shell");
            dynamic shell = Activator.CreateInstance(t);
            dynamic shortcut = shell.CreateShortcut(shortcutPath);
            targetPath = shortcut.TargetPath;
            return targetPath;
        }
    }
}

 

Copyright © 2000-2022 Lzhdim Technology Software All Rights Reserved