C#, WPF - OpenFileDialog does not appear
Asked Answered
P

7

9

I have been searching up and down the web and unfortunately never came across an issue quite like mine, so here goes:

My C# WPF application won't show me no OpenFileDialogs or SafeFileDialogs.

private void btnBrowseNet_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.CheckPathExists = true;
        ofd.Multiselect = false;
        ofd.Title = "Open Network Configuration Batch file...";
        ofd.ValidateNames = true;
        ofd.Filter = "Comma Seperated Value Files|*.csv";

        if (ofd.ShowDialog() == true)
        {
           //...
        }
    }

This exact code does in one occasion exactly what it is supposed to do and hardly five minutes later I can click the button all I want, nothing happens but the mouse pointer turning into a little busy-indicator and then nothing. I can step through the method or do something like this

bool? shown = ofd.ShowDialog();

But no matter what, the dialog won't show. Of course, shown will be false in that case. I wasted one and a half hours searching yesterday and right when I quit I tried it again and all of a sudden it worked. Sometimes it works, sometimes it doesn't. But it seems to be project specific because I can paste the same code into a new project and it works like it is supposed to do. Also, that's the only thing about the project that seems fishy. Everything else works as intended.

Has anyone on here ever experienced something similar and thus an idea of what on earth I could do? Any help weould be highly appreciated.

Priesthood answered 4/2, 2010 at 16:18 Comment(2)
As a point of reference to those answering, this appears to be Microsoft.Win32.OpenFileDialog and not the equivalent System.Windows.Forms.OpenFileDialog.Cyanamide
It's an old question, but I am experiencing the same phenomenon with an VSTO add-in for Excel: "Sometimes it works, sometimes it doesn't." It is totally unpredictable. Unfortunately, neither experimenting with STA threads nor creating (dummy) forms or WPF windows before calling OpenFileDialog.ShowDialog() (as suggested below) prevents this behavior.Granada
M
9

There are a large number of possible failure modes for OpenFileDialog. Using one exposes your app to just about any shell extension that's installed on your machine. Many of which can be very destabilizing, it isn't that likely that the extension author has checked if it works properly in a WPF process.

Tackle this problem by running SysInternals' AutoRuns utility. Click the Explorer tab and look for the groups that have "ShellEx" in their name. Uncheck anything that wasn't published by Microsoft. Reboot and check if the problem is solved.

Maltese answered 4/2, 2010 at 17:0 Comment(1)
Thanks for the advice! Sadly though, as you pointed out, there is a large number of possible failure modes and disabling all third party shell extension was not the one I encountered. Even after turning everything off and rebooting the problem persists. Also, let me point out that the dialogs work in another project at the same time - flawlessly. I would like to vote you answer up, though, as it seems pretty useful to me. Unfortunately I can't do that until I gathered some more rep :PPriesthood
C
7

This happened to me recently. The problem was the Main method wasn't marked as an STAThread which will cause the WPF OpenFileDialog's ShowDialog method to block indefinitely.

static void Main(string[] args)
{
    var openFileDialog = new OpenFileDialog();
    var result = openFileDialog.ShowDialog();
}

will never exit or throw an exception, whereas

[STAThread]    
static void Main(string[] args)
{
    var openFileDialog = new OpenFileDialog();
    var result = openFileDialog.ShowDialog();
}

will work as expected.

Chacma answered 16/9, 2011 at 14:48 Comment(4)
By saying it will block you mean it won't return? Because that's clearly not what's happening at my end. On the contrary, it returns immediately, indicating no Dialog was shown but it only does on random occasions.Priesthood
In Console application it is required to have STAThread for the Dialog to work.Nodose
But WPF is different. And the code seems to be running on the main thread too.Nodose
I'm using XNA game studio instead of WPF and this solved my problem :).Thereabouts
K
3

I am experiencing a similar problem, and as Garrett suggested, it is an STA issue. I have been struggling with STA issues a lot in the past few months, as I need to launch screens from a console window (Testing purposes) - this means that the calling thread is not STA, but can be simulated in something like the following:

    [STAThread]
    private void Execute() {
        try {
            Thread t = new Thread(() => {
                OpenFileDialog dlg = new OpenFileDialog();
                // The following would not return the dialog if the current
                // thread is not STA
                var result = dlg.ShowDialog();
            });

            t.SetApartmentState(ApartmentState.STA);
            t.Start();
        } catch (Exception ex) {
            // Handle the exception
            ex.LogException();
        }
    }

Unforunately, it did not work for me to just mark the method as STAThread, I had to launch the operation in a thread marked as STA.

Ketch answered 28/4, 2016 at 13:40 Comment(1)
This is exactly what helped me, thanks! And yes, just to mark the method with STAThread property was not enough.Diedrediefenbaker
E
2

sometime [staThread] not working, you can try this:

    public void showOpenFileDialog()
    {
        OpenFileDialog im = new OpenFileDialog();
        if (im.ShowDialog() == DialogResult.OK)
        {
            textBox1.Text = im.FileName;
        }
    }


    private void select_button_Click(object sender, EventArgs e)
    {
        Thread newThread = new Thread(new ThreadStart(showOpenFileDialog));
        newThread.SetApartmentState(ApartmentState.STA);
        newThread.Start();
    }
Eskisehir answered 30/3, 2018 at 3:5 Comment(0)
G
1

I know this question was ask in 2010 and the direct answer wasn't the one I'll provide but as today date there is an other reason to have this problem.

I recently installed my software on a fresh virtual machine which works perfectly on my dev computer and many other testing machines.

The Windows 7 virtual machine was too fresh and did not have the SP1 KB976932 installed.

Once installed, I could use the open sand save file dialogs.

I hope this will help someone else.

Galle answered 2/3, 2017 at 18:58 Comment(0)
H
0

Not sure if you figured it out or not, but I recently had this same problem. In my case, the problem was that my application hadn't established an existing window.

My code looked something like this.

private void Application_Startup(object sender, StartupEventArgs e) {
    string startupFileName = String.Empty();
    if ( startupMode = StartupMode.Load ) {
        // open existing file
        OpenFileDialog openDlg = new OpenFileDialog();
        if (openDlg.ShowDialog() != true)
             return;
        startupFileName = openDlg.FileName;
    } else {
        // create a new file
        SaveFileDialog saveDlg = new SaveFileDialog();
        if (saveDlg.ShowDialog() != true)
             return;
        startupFileName = saveDlg.FileName;
    }

    // show my main application window
    MainWindow myMainWindow = new MainWindow(startupFileName);
    myMainWindow.Show();
}

The OpenFileDialog (or SaveFileDialog) would immediately return false without showing because my application had no window for it to attach itself to.

My solution was to put the open/save code after I created my main window but before I called the Show() method.

Hendershot answered 20/9, 2011 at 17:18 Comment(1)
That does not appear to be the problem with my application either as it is guaranteed to have a window established upon creation of the dialog. The user has to click a button to make it appear, so there has to be a window. Or did I misunderstand your answer?Priesthood
N
0

In the console application you will need STAThread appartment for it to work. But WPF is different.

I would advise you using the File Dialogs only after the window starts and the Main Thread starts working. Try showing your dialog in some MainWindow event of its lifecycle.

Nodose answered 11/9, 2012 at 14:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.