Como posso testar programaticamente se um caminho / arquivo é um atalho?
Pergunta
Eu preciso de teste se um arquivo é um atalho. Eu ainda estou tentando descobrir como o material será criado, mas eu só poderia tê-lo do caminho, eu só pode ter o conteúdo real do arquivo (como um byte []) ou eu poderia ter ambos.
Algumas complicações incluem que eu poderia estar em um arquivo zip (nestes casos o caminho será um caminho interno)
Solução
Os atalhos podem ser manipulados usando os objetos COM no SHELL32.DLL.
Em seu projeto Visual Studio, adicione uma referência à biblioteca COM "Controles Microsoft Shell e Automação" e, em seguida, use o seguinte:
/// <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
}
Você pode obter o alvo real do link da seguinte forma:
/// <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
}
Outras dicas
Você pode simplesmente verificar a extensão e / ou conteúdo deste arquivo. Ele contém um GUID especial no cabeçalho.
Leia este documento .
Verifique a extensão? (.Lnk)