I want to grab the target path of an exe from it's shortcut. This seems simple with DereferenceLinks but it's not working. I'm even trying Path.GetDirectoryName and checking if DereferenceLinks is true along with ShowDialog().
OpenFileDialog o = new OpenFileDialog();
o.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
o.Title = "Select the game's exe file or shortcut file";
o.Filter = "Executable or Shortcut (*.exe, *.lnk) | *.exe; *.lnk";
o.DereferenceLinks = true;
if ((bool)o.ShowDialog() && o.DereferenceLinks == true)
{
Debug.WriteLine("o.SafeFileName: " + o.SafeFileName);
Debug.WriteLine("o.FileName: " + o.FileName);
Debug.WriteLine("Path.GetDirectoryName(o.SafeFileName): " + Path.GetDirectoryName(o.SafeFileName));
Debug.WriteLine("Path.GetDirectoryName(o.FileName): " + Path.GetDirectoryName(o.FileName));
}
Can't post images yet so this is the Debug output after selecting a game's shortcut on the desktop. The game's exe is not located in desktop and the filename is clearly still referencing the lnk file.
What am I doing wrong? Am I not understanding the purpose of DereferenceLinks?
The reason why you get not dereferenced file name is that there is an explicit filter for the *.lnk
files.
So if you remove *.lnk
from the filter you will still get the shortcut files to the exe files and FileName
will return the target of the shortcut file.
o.Filter = "Executable or Shortcut (*.exe, *.lnk) | *.exe";