kogh
kogh

Reputation: 1015

How to programatically delete shortcut from user's desktop?

Using C#, how can I delete a shortcut from a user's desktop?

Tried this with no success:

string WinUser = WindowsIdentity.GetCurrent().Name;
WinUser = WinUser.Substring(WinUser.LastIndexOf("\\") + 1);

File.Delete("C:\\Users\\" + WinUser + "\\Desktop\\Touch Data.lnk");

What am I missing? Appreciate any advice on this!

Upvotes: 7

Views: 10364

Answers (4)

skb
skb

Reputation: 1168

I had the same scenario where I had to check if the shortcut exists and then delete it. I used the following code

string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if(System.IO.File.Exists(Path.Combine(desktopPath , "shortcut.lnk")))
{
 System.IO.File.Delete(Path.Combine(desktopPath , "shortcut.lnk"));
}

Upvotes: 1

ugur
ugur

Reputation: 9

System.IO.File.Delete("C:/Users/Public/Desktop/Game.lnk");

:)) win7 standart user name public

Upvotes: 0

Rich O'Kelly
Rich O'Kelly

Reputation: 41767

Try the following:

string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
File.Delete(Path.Combine(desktopPath, "Touch Data.lnk"));

Upvotes: 14

Almo
Almo

Reputation: 15871

I had this issue in this question I asked:

Why does FolderBrowserDialog not allow the desktop as SelectedPath when RootFolder is MyComputer?

The answer I got was this:

Apparently, the Desktop in Win 7 doesn't actually exist at the path

c:\Users\username\Desktop

The system pretends it does at the command prompt and in windows explorer. But since it isn't there, the part of SelectedPath that requires its path to be under RootFolder disallows setting the path in that way.

It's possible this is the issue. You should use the Environment.GetFolderPath function to get a handle on the real desktop. :)

Upvotes: 3

Related Questions