在Microsoft.Win32.OpenFileDialog上调用ShowDialog时出现异常

Mik*_*scu 6 .net wpf exception

我从WPF应用程序获取报告,该应用程序部署在字段中,在尝试显示打开文件对话框时引发以下ArgumentException.

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)
  ...
Run Code Online (Sandbox Code Playgroud)

问题是到目前为止我还没有能够在我的开发环境中复制这个问题,但我收到了一些来自该领域的报告,说明发生了这种异常.

谁看过这个吗?最重要的是你知道原因和/或修复它,除了简单地在它周围放一个try/catch并指示用户再试一次他们试图做的事情吗?

在回复注释时,这是打开对话框的代码(不,这不是检查返回类型的问题).从ShowDialog中抛出异常(请参阅堆栈跟踪):

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..
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ong 7

非特殊目录(例如映射的网络驱动器)也会出现此问题。就我而言,我们的%HOME%环境变量指向映射的网络驱动器 (Z:)。因此,以下代码生成相同的异常:

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));
Run Code Online (Sandbox Code Playgroud)

解决方案:

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));
Run Code Online (Sandbox Code Playgroud)


Mik*_*scu 3

这确实应该交给@Hans Passant,因为他为我指明了正确的方向。

事实证明,一旦我弄清楚问题到底是什么,在我的开发计算机上复制(和修复)这个问题就很简单了。事实证明,问题确实是 InitialDirectory 属性被设置为某个奇怪的值。就我而言,我可以通过将 InitialDirectory 设置为“\”来复制该问题;

这是解决该问题的修改后的代码:

 try
 {
     result = dlg.ShowDialog(Window.GetWindow(this));
 }
 catch{
     dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
     result = dlg.ShowDialog(Window.GetWindow(this));
 }
Run Code Online (Sandbox Code Playgroud)