C#和WPF,Show FIleDialog抛出异常

时间:2013-02-08 14:56:47

标签: c# wpf exception

我的代码有问题。我在我的项目中使用OpenFileDialog,当我调用方法ShowDialog时会抛出异常。我不明白为什么。

    private void open_FileMenu(object sender, RoutedEventArgs e)
    {
        OpenFileDialog browser = new OpenFileDialog();
        browser.AddExtension = true;
        browser.Filter = "Audio, Video File | *.wma; *.mp3; *.wmv";
        browser.Title = "Choose your file";
         if (browser.ShowDialog() == System.Windows.Forms.DialogResult.Yes) // Exception thrown here
          {
            try
            {
                string FileName = browser.FileName;
                MyMedia.Source = new Uri(FileName);
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

这个例外说

    A first chance exception of type 'System.ComponentModel.Win32Exception' occurred  in WindowsBase.dl

其他信息:参数不正确

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:4)

在WinForms CommonDialog.ShowDialog()来自System.Windows.Forms.dll并返回DialogResult

在WPF CommonDialog.ShowDialog()来自PresentationFramework.dll并返回bool?

当然这会导致很多混乱。最终你想要这个。

if (browser.ShowDialog() == true)

答案 1 :(得分:1)

这对我有用:

        OpenFileDialog browser = new OpenFileDialog();
        browser.AddExtension = true;
        browser.Filter = "Audio, Video File | *.wma; *.mp3; *.wmv";
        browser.Title = "Choose your file";
        string FileName;
        bool? res = browser.ShowDialog(); // No exception thrown here
        if (res ?? false)
        {
            try
            {
                 FileName = browser.FileName;
                //MyMedia.Source = new Uri(FileName);
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }