在我的WPF应用程序中,我曾经OpenFileDialog选择一个图像并将其加载到应用程序中,这可以正常工作。
但是,如果我从闪存驱动器运行相同的应用程序,图像会在UI冻结后加载,任何点击UI都会使应用程序崩溃。
我也有manifest应用程序的管理员。
在我的WPF应用程序中,我曾经OpenFileDialog选择一个图像并将其加载到应用程序中,这可以正常工作。
但是,如果我从闪存驱动器运行相同的应用程序,图像会在UI冻结后加载,任何点击UI都会使应用程序崩溃。
我也有manifest应用程序的管理员。
我找不到很好的解释,但我用有效的本地路径设置 InitialDirectory 解决了这个问题(例如,Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
我以前从网络驱动器运行时看到过类似的情况。如果应用程序不是从完全受信任的来源加载的,您可能会收到 SecurityException。
在任何情况下,请尝试在无法查看您是否遇到异常的代码周围添加一个 try/catch 块。
在这种情况下OpenFileDialog会导致应用程序挂起和崩溃。
所以转移OpenFileDialog到一个新线程。一切正常。
我发现这个问题不仅发生在 WPF 中,而且发生在 WinForms 中。很难说问题的根源是什么,但似乎与 OpenFileDialog 相关的 Microsoft dll 有错误(对我来说,它是 CmnDlg32.dll)
我可以调用 ShowDialog() 函数的唯一方法是将它包装在事件中并在
this.BeginInvoke(
        new Action<YourObject, EventArgs>(YourObject_FileDialogOpened), new object[] 
                                                        { YourObjectInstance, e });
其中“this”是一个控件(例如,窗体)。
BeginInvoke(...) 您调用的授权将以适当的方式进行处理。
如果您在按钮单击事件或任何其他类似情况下使用 OpenFileDialog 调用,则不会出现问题。
使用 OpenFileDialog 时 Winform 如何崩溃
using(var ofd = new OpenFileDialog())
{
   ofd.Filter = "Image Files (*.png;*.bmp;*.jpg)|*.png;*.bmp;*.jpg";
   if(ofd.ShowDialog() == DialogResult.OK) // <-- reason of crashing
   {
     PictureBox.Image = Image.FromFile(ofd.FileName);
   }
}
如何解决问题
using(var ofd = new OpenFileDialog())
{
   ofd.Filter = "Image Files (*.png;*.bmp;*.jpg)|*.png;*.bmp;*.jpg";
   DialogResult Action = a.ShowDialog();
   if(Action == DialogResult.OK) // <-- To fix
   {
     PictureBox.Image = Image.FromFile(ofd.FileName);
   }
}
使用这样的东西:
Dispatcher.Invoke(new Action(() =>
            {
                using (SaveFileDialog fd = new SaveFileDialog())
                {
                    var json = JsonConvert.SerializeObject(arScene, Formatting.Indented);
                    var bytes = UTF8Encoding.UTF8.GetBytes(json); // or any byte array data
                    fd.Filter = "JSon files (*.json)|*.json|All files (*.*)|*.*|ARScene (*.ARScene)|*.ARScene";
                    fd.Title = "Save an ARScene File";
                    fd.AutoUpgradeEnabled = true;
                    fd.DefaultExt = "ARScene";
                    fd.OverwritePrompt = false;
                    fd.RestoreDirectory = true;
                    fd.SupportMultiDottedExtensions = true;
                    fd.CreatePrompt = false;
                    if (fd.ShowDialog() == DialogResult.OK)
                    {
                        if (fd.FileName != "")
                        {
                            FileStream fs = (FileStream)fd.OpenFile();
                            if (fs != null)
                            {
                                fs.Write(bytes, 0, bytes.Length);
                                fs.Close();
                            }
                        }
                    }
                    fd.Dispose(); // not needed, but save;-)
                }
}));