FileDialog Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Displays a dialog box from which the user can select a file.
public ref class FileDialog abstract : System::Windows::Forms::CommonDialog
public abstract class FileDialog : System.Windows.Forms.CommonDialog
type FileDialog = class
inherit CommonDialog
Public MustInherit Class FileDialog
Inherits CommonDialog
- Inheritance
- Derived
Examples
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.
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
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.
If you want to enable users to select a folder instead of a file, use the FolderBrowserDialog.
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 Globalization 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.
Important
If the user of your application changes the folder in the FileDialog, then the current working directory for your application is set to the location specified in the FileDialog. To prevent this, set the RestoreDirectory property to true
.
Fields
EventFileOk |
Owns the FileOk event. |
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. |
AddToRecent |
Gets or sets a value indicating whether the dialog box adds the file being opened or saved to the recent list. |
AutoUpgradeEnabled |
Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows Vista. |
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. |
ClientGuid |
Gets or sets the GUID to associate with this dialog state. Typically, state such as the last visited folder and the position and size of the dialog is persisted based on the name of the executable file. By specifying a GUID, an application can have different persisted states for different versions of the dialog within the same application (for example, an import dialog and an open dialog). This functionality is not available if an application is not using visual styles or if AutoUpgradeEnabled is set to |
Container |
Gets the IContainer that contains the Component. (Inherited from Component) |
CustomPlaces |
Gets the custom places collection for this FileDialog instance. |
DefaultExt |
Gets or sets the default file name extension. |
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). |
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. |
FileNames |
Gets the file names of all selected files in the dialog box. |
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. |
FilterIndex |
Gets or sets the index of the filter currently selected in the file dialog box. |
InitialDirectory |
Gets or sets the initial directory displayed by the file dialog box. |
Instance |
Gets the Win32 instance handle for the application. |
OkRequiresInteraction |
Gets or sets a value indicating whether the OK button of the dialog box is disabled until the user navigates the view or edits the filename (if applicable). |
Options |
Gets values to initialize the FileDialog. |
RestoreDirectory |
Gets or sets a value indicating whether the dialog box restores the directory to the previously selected directory before closing. |
ShowHelp |
Gets or sets a value indicating whether the Help button is displayed in the file dialog box. |
ShowHiddenFiles |
Gets or sets a value indicating whether the dialog box displays hidden and system files. |
ShowPinnedPlaces |
Gets or sets a value indicating whether the items shown by default in the view's navigation pane are shown. |
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. |
Tag |
Gets or sets an object that contains data about the control. (Inherited from CommonDialog) |
Title |
Gets or sets the file dialog box title. |
ValidateNames |
Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names. |
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() |
Obsolete.
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. |
InitializeLifetimeService() |
Obsolete.
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. |
OnHelpRequest(EventArgs) |
Raises the HelpRequest event. (Inherited from CommonDialog) |
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. |
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. |
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. |
HelpRequest |
Occurs when the user clicks the Help button on a common dialog box. (Inherited from CommonDialog) |