Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception when calling ShowDialog on a Microsoft.Win32.OpenFileDialog

I'm getting reports from a WPF application that is deployed in the field that the following ArgumentException is being thrown when attempting to display an Open File Dialog.

Exception Message:   Value does not fall within the expected range.
Method Information:  MS.Internal.AppModel.IShellItem2 GetShellItemForPath(System.String)
Exception Source:    PresentationFramework
Stack Trace
  at MS.Internal.AppModel.ShellUtil.GetShellItemForPath(String path)
  at Microsoft.Win32.FileDialog.PrepareVistaDialog(IFileDialog dialog)
  at Microsoft.Win32.FileDialog.RunVistaDialog(IntPtr hwndOwner)
  at Microsoft.Win32.FileDialog.RunDialog(IntPtr hwndOwner)
  at Microsoft.Win32.CommonDialog.ShowDialog(Window owner)
  ...

The problem is that so far I haven't been able to replicate this in my development environment but I have received several reports from the field that this exception is occurring.

Has anyone seen this before? And most importantly do you know the cause and/or a fix for it other than just simply putting a try/catch around it and instructing the user to try again whatever it is they were trying to do?

In response to a comment, this is the code that opens the dialog (and no, it was not a problem of checking the return type). The exception is thrown from within ShowDialog (see stack trace):

Nullable<bool> result = null;

var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".txt";
dlg.Filter = "Text Files (.txt)|*.txt|All Files|*.*";
dlg.Title = "Open File";
dlg.Multiselect = false;
dlg.InitialDirectory = GetFolderFromConfig("folders.templates");
result = dlg.ShowDialog(Window.GetWindow(this));

if (result == true)
{
    // Invokes another method here..
}
like image 705
Mike Dinescu Avatar asked Jan 07 '13 21:01

Mike Dinescu


1 Answers

This issue can also occur with non-special directories, such as mapped network drives. In my case, our %HOME% environment variable points to a mapped network drive (Z:). Thus the following code generates the same exception:

Nullable<bool> result = null;

var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".txt";
dlg.Filter = "Text Files (.txt)|*.txt|All Files|*.*";
dlg.Title = "Open File";
dlg.Multiselect = false;
dlg.InitialDirectory = Environment.GetEnvironmentVariable("Home")+@"\.ssh"; // boom
result = dlg.ShowDialog(Window.GetWindow(this));

Solution:

var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".txt";
dlg.Filter = "Text Files (.txt)|*.txt|All Files|*.*";
dlg.Title = "Open File";
dlg.Multiselect = false;
dlg.InitialDirectory = System.IO.Path.GetFullPath(Environment.GetEnvironmentVariable("Home")+@"\.ssh"); // no boom
result = dlg.ShowDialog(Window.GetWindow(this));
like image 114
Nathan Strong Avatar answered Sep 28 '22 08:09

Nathan Strong