Question

I'm trying to create a little program which retrieves to the user the target filename of shortcut in C#(Console Application). My code works without errors, but it doesn't giving me the correct result.

This is my code: (took from: http://snipplr.com/view/47974)

private static string GetTargetPath(string ShortcutPath)
{
    string pathOnly = System.IO.Path.GetDirectoryName(ShortcutPath);
    string filenameOnly = System.IO.Path.GetFileName(ShortcutPath);

    Shell32.Shell shell = new Shell32.ShellClass();
    Shell32.Folder folder = shell.NameSpace(pathOnly);
    Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
    if (folderItem != null)
    {
        Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
        return link.Path;
    }
    return ""; // not found
}

As I said, the code retrieving me wrong output (an empty string), even if the file is exists. for example, I tired to get the target file of some shortcut in the path: C:\Users\Admin123\AppData\Roaming\Microsoft\Office\Recent

What can be the cause of this problem? and how can I solve it?

EDIT

I tried the same code again and now it works ! Thanks to everyone ! :)

Was it helpful?

Solution

Well, I see no problems with your code. Tested and it works well.

I created two links: boot.lnk and prestigio_notes.lnk, both leading to proper files. Their output was:

D:\Boot1.asm and D:\Dokumenty\Android\Prestigio\doc\prestigio_notes.txt respectively.

This is the code I used (sorry for copy-pasting the function once again, but I want it to be a complete and clear class):

class Program {
    static void Main(string[] args) {
        Console.WriteLine(GetTargetPath(@"D:\boot.lnk"));
        Console.WriteLine(GetTargetPath(@"D:\prestigio_notes.lnk"));
        Console.ReadLine();
    }

    private static string GetTargetPath(string ShortcutPath) {
        string pathOnly = System.IO.Path.GetDirectoryName(ShortcutPath);
        string filenameOnly = System.IO.Path.GetFileName(ShortcutPath);

        Shell32.Shell shell = new Shell32.Shell();
        Shell32.Folder folder = shell.NameSpace(pathOnly);
        Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
        if (folderItem != null) {
            Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
            return link.Path;
        }
        return ""; // not found
    }
}

Check that you are referencing proper COM object from the available references list. If it fails, check that you have rights to read from specified location.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top