OpenFileDialog Class

Definition

Displays a standard dialog box that prompts the user to open a file. This class cannot be inherited.

public ref class OpenFileDialog sealed : System::Windows::Forms::FileDialog
public sealed class OpenFileDialog : System.Windows.Forms.FileDialog
type OpenFileDialog = class
    inherit FileDialog
Public NotInheritable Class OpenFileDialog
Inherits FileDialog
Inheritance

Examples

The following code example creates an OpenFileDialog, sets several properties to define the file extension filter and dialog behavior, and displays the dialog box using the CommonDialog.ShowDialog method. The example requires a form with a Button placed on it and a reference to the System.IO namespace added to it.

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() == System::Windows::Forms::DialogResult::OK )
      {
         if ( (myStream = openFileDialog1->OpenFile()) != nullptr )
         {
            // Insert code to read the stream here.
            myStream->Close();
         }
      }
   }
var fileContent = string.Empty;
var filePath = string.Empty;

using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
    openFileDialog.InitialDirectory = "c:\\";
    openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
    openFileDialog.FilterIndex = 2;
    openFileDialog.RestoreDirectory = true;

    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        //Get the path of specified file
        filePath = openFileDialog.FileName;

        //Read the contents of the file into a stream
        var fileStream = openFileDialog.OpenFile();

        using (StreamReader reader = new StreamReader(fileStream))
        {
            fileContent = reader.ReadToEnd();
        }
    }
}

MessageBox.Show(fileContent, "File Content at path: " + filePath, MessageBoxButtons.OK);
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

Remarks

This class allows you to check whether a file exists and to open it. The ShowReadOnly property determines whether a read-only check box appears in the dialog box. The ReadOnlyChecked property indicates whether the read-only check box is checked.

Most of the core functionality for this class is found in the FileDialog class.

On a right-to-left operating system, setting the containing form's RightToLeft property to RightToLeft.Yes localizes the dialog's File Name, Open, and Cancel buttons. If the property is not set to RightToLeft.Yes, English text is used instead.

If you want to give the user the ability to select a folder instead of a file, use FolderBrowserDialog instead.

Constructors

OpenFileDialog()

Initializes an instance of the OpenFileDialog class.

Properties

AddExtension

Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.

(Inherited from FileDialog)
AutoUpgradeEnabled

Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows Vista.

(Inherited from FileDialog)
CanRaiseEvents

Gets a value indicating whether the component can raise an event.

(Inherited from Component)
CheckFileExists

Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.

CheckPathExists

Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.

(Inherited from FileDialog)
Container

Gets the IContainer that contains the Component.

(Inherited from Component)
CustomPlaces

Gets the custom places collection for this FileDialog instance.

(Inherited from FileDialog)
DefaultExt

Gets or sets the default file name extension.

(Inherited from FileDialog)
DereferenceLinks

Gets or sets a value indicating whether the dialog box returns the location of the file referenced by the shortcut or whether it returns the location of the shortcut (.lnk).

(Inherited from FileDialog)
DesignMode

Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Events

Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
FileName

Gets or sets a string containing the file name selected in the file dialog box.

(Inherited from FileDialog)
FileNames

Gets the file names of all selected files in the dialog box.

(Inherited from FileDialog)
Filter

Gets or sets the current file name filter string, which determines the choices that appear in the "Save as file type" or "Files of type" box in the dialog box.

(Inherited from FileDialog)
FilterIndex

Gets or sets the index of the filter currently selected in the file dialog box.

(Inherited from FileDialog)
InitialDirectory

Gets or sets the initial directory displayed by the file dialog box.

(Inherited from FileDialog)
Instance

Gets the Win32 instance handle for the application.

(Inherited from FileDialog)
Multiselect

Gets or sets a value indicating whether the dialog box allows multiple files to be selected.

Options

Gets values to initialize the FileDialog.

(Inherited from FileDialog)
ReadOnlyChecked

Gets or sets a value indicating whether the read-only check box is selected.

RestoreDirectory

Gets or sets a value indicating whether the dialog box restores the directory to the previously selected directory before closing.

(Inherited from FileDialog)
SafeFileName

Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

SafeFileNames

Gets an array of file names and extensions for all the selected files in the dialog box. The file names do not include the path.

ShowHelp

Gets or sets a value indicating whether the Help button is displayed in the file dialog box.

(Inherited from FileDialog)
ShowReadOnly

Gets or sets a value indicating whether the dialog box contains a read-only check box.

Site

Gets or sets the ISite of the Component.

(Inherited from Component)
SupportMultiDottedExtensions

Gets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions.

(Inherited from FileDialog)
Tag

Gets or sets an object that contains data about the control.

(Inherited from CommonDialog)
Title

Gets or sets the file dialog box title.

(Inherited from FileDialog)
ValidateNames

Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names.

(Inherited from FileDialog)

Methods

CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose()

Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean)

Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component)
Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type)

Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
HookProc(IntPtr, Int32, IntPtr, IntPtr)

Defines the common dialog box hook procedure that is overridden to add specific functionality to the file dialog box.

(Inherited from FileDialog)
InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
OnFileOk(CancelEventArgs)

Raises the FileOk event.

(Inherited from FileDialog)
OnHelpRequest(EventArgs)

Raises the HelpRequest event.

(Inherited from CommonDialog)
OpenFile()

Opens the file selected by the user, with read-only permission. The file is specified by the FileName property.

OwnerWndProc(IntPtr, Int32, IntPtr, IntPtr)

Defines the owner window procedure that is overridden to add specific functionality to a common dialog box.

(Inherited from CommonDialog)
Reset()

Resets all properties to their default values.

RunDialog(IntPtr)

Specifies a common dialog box.

(Inherited from FileDialog)
ShowDialog()

Runs a common dialog box with a default owner.

(Inherited from CommonDialog)
ShowDialog(IWin32Window)

Runs a common dialog box with the specified owner.

(Inherited from CommonDialog)
ToString()

Provides a string version of this object.

(Inherited from FileDialog)

Events

Disposed

Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
FileOk

Occurs when the user clicks on the Open or Save button on a file dialog box.

(Inherited from FileDialog)
HelpRequest

Occurs when the user clicks the Help button on a common dialog box.

(Inherited from CommonDialog)

Applies to

See also