How do you get the directory target of a shortcut folder? I\'ve search everywhere and only finds target of shortcut file.
I think you will need to use COM and add a reference to "Microsoft Shell Control And Automation", as described in this blog post:
Here's an example using the code provided there:
namespace Shortcut
{
using System;
using System.Diagnostics;
using System.IO;
using Shell32;
class Program
{
public static string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell shell = new Shell();
Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return string.Empty;
}
static void Main(string[] args)
{
const string path = @"C:\link to foobar.lnk";
Console.WriteLine(GetShortcutTargetFile(path));
}
}
}
Thanks to Mohsen.Sharify's answer I got more neat piece of code:
var fileName = Process.GetCurrentProcess().MainModule.FileName;
var folderName = Path.Combine(fileName, ".."); //origin folder
All file shortcuts have a .lnk file extension you can check for. Using a string for example, you could use string.EndsWith(".lnk") as a filter.
All URL shortcuts have a .url file extension, so you will need to account for those as well if needed.
If you don't want to use dependencies you can use https://blez.wordpress.com/2013/02/18/get-file-shortcuts-target-with-c/ But lnk format is undocumented, so do it only if you understand risks.
In windows 10 it needs to be done like this, first add COM reference to "Microsoft Shell Control And Automation"
// new way for windows 10
string targetname;
string pathOnly = System.IO.Path.GetDirectoryName(LnkFileName);
string filenameOnly = System.IO.Path.GetFileName(LnkFileName);
Shell shell = new Shell();
Shell32.Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null) {
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
targetname = link.Target.Path; // <-- main difference
if (targetname.StartsWith("{")) { // it is prefixed with {54A35DE2-guid-for-program-files-x86-QZ32BP4}
int endguid = targetname.IndexOf("}");
if (endguid > 0) {
targetname = "C:\\program files (x86)" + targetname.Substring(endguid + 1);
}
}
if you want find your application path that has shortcut on desktop, an easy way that i use, is the following:
Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\\")
this code return any exe path that is running,Regardless that who requested file