How does one use OpenFileDialog in C# in visual Studio 2010

xarzu picture xarzu · May 7, 2010 · Viewed 16.8k times · Source

I have written a custom dialog (form) that I can use in a C# program that behaves much like a "File - Open" menu command and brings up a window where a user can select a file or directory.

The question I have is this. It has "My Computer" as its root. How can I have it so that it searches on a Network? If the file or directory is located on a network.

Or better yet, in Visual Studio 2010, is there some sort of canned FileOpenDialog that I can use right away?

I tried calling the OpenFileDialog as described in the example code at http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspx but the compiler does not seem to like DialogResult.OK as used in this line of code:

if(openFileDialog1.ShowDialog() == DialogResult.OK)

The compiler says:

Error 1 'System.Nullable' does not contain a definition for 'OK' and no extension method 'OK' accepting a first argument of type 'System.Nullable' could be found (are you missing a using directive or an assembly reference?)

I tried using the namespace Microsoft.Win32 instead of System.Windows.Forms and neither worked. They both produced this error.

Answer

Henk Holterman picture Henk Holterman · May 7, 2010

Looks like you are trying to use a WinForms (System.Windows.Forms) dialog.
Here is the MSDN page for WPF dialog boxes from the Microsoft.Win32 namespace.

An excerpt:

Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension

// Show open file dialog box
bool? result = dlg.ShowDialog();