在net的c#中如何通过快捷方式,获取程序的所在路径?其实快捷方式也是为了方便用户打开,而对应用程序做的一个映射,本质上还是指向应用程序所在路径的。今天就用代码实现这个功能,好像用到的地方不太多,就当装个X好了,出去可以忽悠忽悠小白。
我们先把快捷方式放到一个文件夹里,然后调用下面的代码即可
string folder = @"D:\NaviOther\快捷方式2\常用程序"; Dictionary<string, string> dicP1 = FileHelper.GetAppPathByShortcut(folder); Dictionary<string, string> dicP2 = FileHelper.GetAppPathByShortcut(folder, "navicat.exe");
实现的代码
/// <summary>
/// 根据快捷方式,获取程序所在路径
/// </summary>
/// <param name="folder"></param>
/// <param name="shortCutName"></param>
/// <returns></returns>
public static Dictionary<string, string> GetAppPathByShortcut(string folder, string shortCutName = "")
{
Dictionary<string, string> dicP = new Dictionary<string, string>();
string driver = folder.Substring(0, 2);
folder = folder.Substring(2) + "\\";
folder = folder.Replace("\\", "\\\\");
string wsql = "Select * From Win32_ShortcutFile Where Drive='" + driver + "' and Path='" + folder + "'";
if (!string.IsNullOrEmpty(shortCutName))
{
wsql += " and FileName = '" + shortCutName + "'";
}
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wsql);
if (searcher == null)
return dicP;
foreach (ManagementObject o in searcher.Get())
{
string shortcut = o.GetPropertyValue("Name").ToString();
string filePath = o.GetPropertyValue("Target").ToString();
dicP.Add(shortcut, filePath);
}
return dicP;
}
相关阅读

文章评论