不要忘記將Embed Interop Types設置爲False來引用Interop.IWshRuntimeLibrary。 我測試過並沒有收到錯誤。
// Make sure you use try/catch block because your App may has no permissions on the target path!
try
{
CreateShortcut(@"C:\temp", @"C:\MyShortcutFile.lnk",
"Custom Shortcut", "/param", "Ctrl+F", @"c:\");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
/// <summary>
/// Create Windows Shorcut
/// </summary>
/// <param name="SourceFile">A file you want to make shortcut to</param>
/// <param name="ShortcutFile">Path and shorcut file name including file extension (.lnk)</param>
public static void CreateShortcut(string SourceFile, string ShortcutFile)
{
CreateShortcut(SourceFile, ShortcutFile, null, null, null, null);
}
/// <summary>
/// Create Windows Shorcut
/// </summary>
/// <param name="SourceFile">A file you want to make shortcut to</param>
/// <param name="ShortcutFile">Path and shorcut file name including file extension (.lnk)</param>
/// <param name="Description">Shortcut description</param>
/// <param name="Arguments">Command line arguments</param>
/// <param name="HotKey">Shortcut hot key as a string, for example "Ctrl+F"</param>
/// <param name="WorkingDirectory">"Start in" shorcut parameter</param>
public static void CreateShortcut(string TargetPath, string ShortcutFile, string Description,
string Arguments, string HotKey, string WorkingDirectory)
{
// Check necessary parameters first:
if (String.IsNullOrEmpty(TargetPath))
throw new ArgumentNullException("TargetPath");
if (String.IsNullOrEmpty(ShortcutFile))
throw new ArgumentNullException("ShortcutFile");
// Create WshShellClass instance:
var wshShell = new WshShellClass();
// Create shortcut object:
IWshRuntimeLibrary.IWshShortcut shorcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(ShortcutFile);
// Assign shortcut properties:
shorcut.TargetPath = TargetPath;
shorcut.Description = Description;
if (!String.IsNullOrEmpty(Arguments))
shorcut.Arguments = Arguments;
if (!String.IsNullOrEmpty(HotKey))
shorcut.Hotkey = HotKey;
if (!String.IsNullOrEmpty(WorkingDirectory))
shorcut.WorkingDirectory = WorkingDirectory;
// Save the shortcut:
shorcut.Save();
}
來源:http://zayko.net/post/How-to-create-Windows-shortcut-(C).aspx
可能重複:http://stackoverflow.com/questions/3391923/placing-a-shortcut-in-users-
下面的代碼片段將在桌面上創建一個快捷方式到網絡文件夾啓動文件夾以啓動Windows – 2012-10-22 20:33:11
爲了擺脫歧義錯誤,請確保何時使用.NET File類,調用System.IO.File,並在使用其他類時使用IWShRuntimeLibrary.File 。如果我想在使用System.Windows.Forms和System.Threading的類中使用Timer,因爲它們都包含Timer類,所以我一直都會遇到這個問題。抱歉,我無法幫助您解決主要問題。 –
@ademing2,我有點想到這是我必須做的,但在添加之前,我的所有System.IO.File方法調用之前,我想看看我是否在正確的軌道上。雖然 – swabs