Comment puis-je tester par programme si un chemin / fichier est un raccourci?
Question
Je dois tester si un fichier est un raccourci. J'essaie toujours de comprendre comment les choses vont être configurées, mais je n'ai peut-être que son chemin, je n'ai que le contenu réel du fichier (sous forme d'octet []), ou les deux.
Quelques complications incluent le fait que cela pourrait être dans un fichier zip (dans ce cas, le chemin sera un chemin interne)
La solution
Les raccourcis peuvent être manipulés à l'aide des objets COM dans SHELL32.DLL.
Dans votre projet Visual Studio, ajoutez une référence à la bibliothèque COM "Microsoft Shell Controls And Automation". puis utilisez les éléments suivants:
/// <summary>
/// Returns whether the given path/file is a link
/// </summary>
/// <param name="shortcutFilename"></param>
/// <returns></returns>
public static bool IsLink(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(pathOnly);
Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
return folderItem.IsLink;
}
return false; // not found
}
Vous pouvez obtenir la cible réelle du lien comme suit:
/// <summary>
/// If path/file is a link returns the full pathname of the target,
/// Else return the original pathnameo "" if the file/path can't be found
/// </summary>
/// <param name="shortcutFilename"></param>
/// <returns></returns>
public static string GetShortcutTarget(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(pathOnly);
Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
if (folderItem.IsLink)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return shortcutFilename;
}
return ""; // not found
}
Autres conseils
Vous pouvez simplement vérifier l’extension et / ou le contenu de ce fichier. Il contient un GUID spécial dans l'en-tête.
Lisez ce document .
Vérifiez l'extension? (.lnk)