C#代码创建桌面快捷方式,win10系统报错,代码如下

云顶F 2018-04-10 03:23:47

static void Main(string[] args)
{
CreateDesktopLnkMethod(AppDomain.CurrentDomain.BaseDirectory + "favicon.ico", AppDomain.CurrentDomain.BaseDirectory + "test.exe", "测试2下");
Console.WriteLine("创建成功");
Console.ReadKey();
}

[DllImport("shfolder.dll", CharSet = CharSet.Auto)]
private static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);
private const int MAX_PATH = 260;
private const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019;
/// <summary>
/// 获取公共桌面路径
/// </summary>
/// <returns>返回桌面完整路径</returns>
public static string GetAllUsersDesktopFolderPath()
{
StringBuilder sbPath = new StringBuilder(MAX_PATH);
SHGetFolderPath(IntPtr.Zero, CSIDL_COMMON_DESKTOPDIRECTORY, IntPtr.Zero, 0, sbPath);
return sbPath.ToString();
}

/// <summary>
/// 创建桌面快捷方式,如已存在先删除再创建
/// </summary>
/// <param name="iconPath">icon图标路径</param>
/// <param name="ClientExeFullPath">程序启动路径,带*.exe</param>
/// <param name="lnkName">快捷方式名称</param>
public static void CreateDesktopLnkMethod(string iconPath, string ClientExeFullPath, string lnkName)
{
if (System.IO.File.Exists(iconPath))
{
WshShell shelllnk = new WshShell();
IWshShortcut shortcut = null;
try
{
string[] fi = System.IO.Directory.GetFiles(GetAllUsersDesktopFolderPath());
//string[] fi = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory));
foreach (var item in fi)
{
if (item.IndexOf(".lnk") > -1)
{
shortcut = (IWshShortcut)shelllnk.CreateShortcut(item);
if (shortcut.WorkingDirectory.Equals(AppDomain.CurrentDomain.BaseDirectory))
{//删除原有快捷方式
if (lnkName.Length <= 0)
{
lnkName = shortcut.FullName.Substring(shortcut.FullName.LastIndexOf("\\") + 1, shortcut.FullName.LastIndexOf(".") - shortcut.FullName.LastIndexOf("\\") - 1);
}
System.IO.File.Delete(item);
shortcut = null;
break;
}
}
shortcut = null;
}

//生成新的快捷方式
shortcut = (IWshShortcut)shelllnk.CreateShortcut(GetAllUsersDesktopFolderPath() + "\\" + lnkName + ".lnk");
shortcut.TargetPath = ClientExeFullPath;
shortcut.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
shortcut.WindowStyle = 1;
shortcut.Description = lnkName;
shortcut.IconLocation = iconPath;
shortcut.Save();
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
}
...全文
262 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧