3

I am using C# to access the most recent files on a system and copy them via

Environment.SpecialFolder.Recent

The recent folder in Windows however just creates shortcuts to the actual location of the file. How would one go about copying the file that the shortcut is pointing at as opposed to the shortcut itself?

Many Thanks in advance for any help

Joe
  • 41,484
  • 20
  • 104
  • 125
Ben Collins
  • 221
  • 1
  • 4
  • 12
  • possible duplicate of [How to resolve a .lnk in c#](http://stackoverflow.com/questions/139010/how-to-resolve-a-lnk-in-c) – ChrisF Oct 12 '11 at 11:48

3 Answers3

1

I found and altered this code, works for me:

static string GetShortcutTargetFile(string shortcutFilename)
{
    string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
    string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);

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

    return ""; // not found, use if (File.Exists()) in the calling code
    // or remove the return and throw an exception here if you like
}

You have to add a reference to the Microsoft Shell Controls And Automation COM object (Shell32.dll) to the project to make this work.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Where is `Shell32` in the BCL? – spender Oct 12 '11 at 11:56
  • 1
    Seems reasonable, but beware of issues with objects requiring admin rights to access. See http://stackoverflow.com/questions/2934420/why-do-i-get-e-accessdenied-when-reading-public-shortcuts-through-shell32 for details. – corvuscorax Oct 12 '11 at 12:00
0

This is a similar question that was asked a while ago, but the first answer provides some code that will do what you want as far as resolving the target file / folder name.

How to resolve a .lnk in c#

From there, you would simply go through your list of shortcuts, resolve their linked location, and use File.Copy(linkPath, copyPath); to finish the job.

Community
  • 1
  • 1
A.R.
  • 15,405
  • 19
  • 77
  • 123
0

Maybe this sample code can help you to get the target link out of a .lnk file.

Oliver
  • 43,366
  • 8
  • 94
  • 151