Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
FileDialog Class
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
FileDialog Class

Updated: November 2007

Displays a dialog box from which the user can select a file.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

Visual Basic (Declaration)
Public MustInherit Class FileDialog _
    Inherits CommonDialog
Visual Basic (Usage)
Dim instance As FileDialog
C#
public abstract class FileDialog : CommonDialog
Visual C++
public ref class FileDialog abstract : public CommonDialog
J#
public abstract class FileDialog extends CommonDialog
JScript
public abstract class FileDialog extends CommonDialog

FileDialog is an abstract class that contains common behavior for the OpenFileDialog and SaveFileDialog classes. It is not intended to be used directly but contains common behavior for those two classes. You cannot create an instance of FileDialog. Although the class is declared public, you cannot inherit from it, as it contains internal abstract methods. To create a dialog box to select or save a file, use OpenFileDialog or SaveFileDialog.

FileDialog is a modal dialog box; therefore, when shown, it blocks the rest of the application until the user has chosen a file. When a dialog box is displayed modally, no input (keyboard or mouse click) can occur except to objects on the dialog box. The program must hide or close the dialog box (usually in response to some user action) before input to the calling program can occur.

Caution:

When you use classes derived from FileDialog, such as OpenFileDialog and SaveFileDialog, avoid using string literals containing absolute paths. Instead, dynamically obtain the path using one or more of the techniques described in the following table.

Depending upon the type of application, how data associated with the application is stored, and the reason for accessing the file system, there are many possible ways in which you can create a directory path. The following table shows the techniques for creating paths dynamically.

Path or program category

Class and members to use

Standard Windows paths, such as Program Files, MyDocuments, the Desktop and so on

The System..::.Environment class is the most complete source for these, either through its static methods, such as SystemDirectory, or through the GetFolderPath method, using one of the Environment..::.SpecialFolder enumerated values.

Paths related to the current application

The Application class has static members to obtain certain paths, such as StartupPath, ExecutablePath, LocalUserAppDataPath, and CommonAppDataPath.

The GetTempPath method of the System.IO..::.Path returns the path of the temporary folder.

The GetCurrentDirectory method of the System.IO..::.Directory class returns the application's current executing directory.

The RootDirectory property of the DriveInfo class represents the specified drive's root directory.

Paths stored as application settings

Access the corresponding applications settings property of the wrapper class derived from ApplicationSettingsBase. For more information, see Application Settings for Windows Forms.

Registry storage

Some applications store directory information in the registry. The Application class has the CommonAppDataPath and LocalUserAppDataPath properties that resolve to a RegistryKey value.

ClickOnce applications

For ClickOnce applications, use Application class members such as UserAppDataPath, which will return a pointer to the ClickOnce data directory. For more information, see Accessing Local and Remote Data in ClickOnce Applications.

International applications

For international applications, retrieve the relative path portion from a string resource in your application by using the System.Resources..::.ResourceReader class. For more information about globalization and localization, see the topic Encoding and Localization.

Notice that a full path may be built up using one or more of the described techniques. For example, the GetFolderPath method might be used to obtain the path to the MyDocuments folder, then an application setting may be used to add a relative subdirectory portion.

The System.IO..::.Path class contains static members to assist in manipulating absolute and relative path strings, whereas the System.IO..::.File and System.IO..::.Directory classes have static members that actually manipulate files and directories, respectively.

The following code example uses the OpenFileDialog implementation of FileDialog and illustrates creating, setting of properties, and showing the dialog box. The example uses the ShowDialog method to display the dialog box and return the DialogResult. The example requires a form with a Button placed on it and the System.IO namespace added to it.

Visual Basic
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim myStream As Stream = Nothing
    Dim openFileDialog1 As New OpenFileDialog()

    openFileDialog1.InitialDirectory = "c:\"
    openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
    openFileDialog1.FilterIndex = 2
    openFileDialog1.RestoreDirectory = True

    If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
        Try
            myStream = openFileDialog1.OpenFile()
            If (myStream IsNot Nothing) Then
                ' Insert code to read the stream here.
            End If
        Catch Ex As Exception
            MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
        Finally
            ' Check this again, since we need to make sure we didn't throw an exception on open.
            If (myStream IsNot Nothing) Then
                myStream.Close()
            End If
        End Try
    End If
End Sub


C#
private void button1_Click(object sender, System.EventArgs e)
{
    Stream myStream = null;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "c:\\" ;
    openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
    openFileDialog1.FilterIndex = 2 ;
    openFileDialog1.RestoreDirectory = true ;

    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        try
        {
            if ((myStream = openFileDialog1.OpenFile()) != null)
            {
                using (myStream)
                {
                    // Insert code to read the stream here.
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
        }
    }
}


Visual C++
private:
   void button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      Stream^ myStream;
      OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;

      openFileDialog1->InitialDirectory = "c:\\";
      openFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
      openFileDialog1->FilterIndex = 2;
      openFileDialog1->RestoreDirectory = true;

      if ( openFileDialog1->ShowDialog() == ::DialogResult::OK )
      {
         if ( (myStream = openFileDialog1->OpenFile()) != nullptr )
         {
            // Insert code to read the stream here.
            myStream->Close();
         }
      }
   }

J#
protected void button1_Click(Object sender, System.EventArgs e)
{
    Stream myStream;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.set_InitialDirectory("c:\\");
    openFileDialog1.set_Filter(
        "txt files (*.txt)|*.txt|All files (*.*)|*.*");
    openFileDialog1.set_FilterIndex(2);
    openFileDialog1.set_RestoreDirectory(true);
    if (openFileDialog1.ShowDialog().Equals(get_DialogResult().OK)) {
        if ((myStream = openFileDialog1.OpenFile()) != null) {
            // Insert code to read the stream here.
            myStream.Close();
        }
    }
} //button1_Click

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Pocket PC

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker