3

I have a problem with my code. I use OpenFileDialog in my project and when I call the method ShowDialog an exception is thrown. I don't understand why.

    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);
            }
        }

This exception said

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

Additional information: Incorrect parameter

Someone can help me ?

Gims
  • 65
  • 2
  • 7

2 Answers2

4

In WinForms CommonDialog.ShowDialog() comes from System.Windows.Forms.dll and returns a DialogResult.

In WPF CommonDialog.ShowDialog() comes from PresentationFramework.dll and returns a bool?

Naturally this leads to a lot of confusion. Ultimately you want this instead.

if (browser.ShowDialog() == true)
Cameron MacFarland
  • 70,676
  • 20
  • 104
  • 133
1

This works for me:

        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);
            }
        }
Martin Clarke
  • 5,636
  • 7
  • 38
  • 58