Search code examples
c#.netopenfiledialog

Can the .NET OpenFileDialog be setup to allow the user to select a .lnk file


I want to show a dialog that will allow the user to select a shortcut (.lnk) file. My problem is that the dialog tries to get the file/URL the shortcut is pointing to rather then the .lnk file itself.

How can I make it allow .lnk files to be selected?


Solution

  • You can use the OpenFileDialog.DereferenceLinks property to influence that behaviour (see doc).

    var dlg = new OpenFileDialog();
    dlg.FileName = null;
    dlg.DereferenceLinks = false;
    
    if (dlg.ShowDialog() == DialogResult.OK) {
        this.label1.Text = dlg.FileName;
    }
    

    or

    var dlg = new OpenFileDialog();
    dlg.FileName = null; 
    this.openFileDialog1.Filter = "Link (*.lnk)|*.lnk";
    
    if (dlg.ShowDialog() == DialogResult.OK) {
        this.label1.Text = dlg.FileName;
    

    Both methods yield a .lnk file, however the first approach allows the selection of .lnk files or normal files, while the second only selects .lnk files.