views:

26

answers:

1

I'm trying to read the targets of all desktop shortcuts in a C# 4 application. The shortcuts on a windows desktop can come from more that one location, depending on whether the shortcut is created for all users or just the current user. In this specific case I'm trying to read a shortcut from the public desktop, e.g. from C:\Users\Public\Desktop\shortcut.lnk.

The code is like this (path is a string contaning the path to the lnk file):

var shell = new Shell32.ShellClass();
var folder = shell.NameSpace(Path.GetDirectoryName(path));
var folderItem = folder.ParseName(Path.GetFileName(path));
if (folderItem != null)
{
    var link = (Shell32.ShellLinkObject)folderItem.GetLink;

The last line throws an System.UnauthorizedAccessException, indicating that it's not allowed to read the shortcut file's contents. I have tried on shortcut files on the user's private desktop (c:\Users\username\Desktop) and that works fine.

So, my questions are:

(1) why is my application not allowed to /read/ the shortcut from code, when I can clearly read the contents as a user?

(2) is there a way to get around this? Maybe using a special manifest file for the application?

And, by the way, my OS is Windows 7, 64-bit.

be well

-h-

+1  A: 

Yes, you cannot get access to the .lnk file in that folder by default. You are creating a COM object that allows you to modify the .lnk properties. And that requires an administrator level account with UAC turned off.

Yes, you can fix that with a manifest.

Hans Passant
Great, that worked, thanks a lot - however I'm not sure I see the logic of throwing the exception before I actually try to modify something. Especially since I can easily read the values through the Windows UI without getting an elevation prompt.
corvuscorax
You are using a 15 year old COM interface, invented *long* before UAC was envisioned. It doesn't have a "EnableChangingProperties" property, which when set to False would allow readonly access to the .lnk files. The property sheet handler in Explorer uses something else. Not sure what, but I doubt it is scriptable. The shell interfaces are too old to be easily usable from .NET, only C/C++ programs can.
Hans Passant