FileDialog FileDialog FileDialog FileDialog Class

定义

显示一个用户可从中选择文件的对话框窗口。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
继承
派生

示例

下面的代码示例使用OpenFileDialog的实现FileDialog并说明了创建、 设置的属性,以及显示的对话框。The following code example uses the OpenFileDialog implementation of FileDialog and illustrates creating, setting of properties, and showing the dialog box. 该示例使用ShowDialog方法以显示该对话框并返回DialogResultThe example uses the ShowDialog method to display the dialog box and return the DialogResult. 该示例需要一个具有窗体Button在其上放置和System.IO命名空间添加到它。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

注解

FileDialog 是一个抽象类包含用于常见行为OpenFileDialogSaveFileDialog类。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. 不能创建的实例FileDialogYou cannot create an instance of FileDialog. 尽管在类声明为公共的但您不能从它继承,因为它包含内部的抽象方法。Although the class is declared public, you cannot inherit from it, as it contains internal abstract methods. 若要创建一个对话框来选择或保存的文件,请使用OpenFileDialogSaveFileDialogTo create a dialog box to select or save a file, use OpenFileDialog or SaveFileDialog.

FileDialog 是模式对话框;因此,显示时,它会阻止应用程序的其余部分直到用户已选择一个文件。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.

注意

当您将类派生自FileDialog,如OpenFileDialogSaveFileDialog,避免使用包含绝对路径的字符串文本。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.

如果你想要使用户能够选择而不是文件的文件夹,请使用FolderBrowserDialogIf 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
标准 Windows 路径,如 Program Files、 MyDocuments、 桌面等Standard Windows paths, such as Program Files, MyDocuments, the Desktop and so on System.Environment类是最完整源对于这些数据,通过其静态方法,如SystemDirectory,或通过GetFolderPath方法,使用其中一个Environment.SpecialFolder枚举值。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 Application类具有静态成员,若要获取特定路径,例如StartupPathExecutablePathLocalUserAppDataPath,和CommonAppDataPathThe Application class has static members to obtain certain paths, such as StartupPath, ExecutablePath, LocalUserAppDataPath, and CommonAppDataPath.

GetTempPath方法的System.IO.Path返回临时文件夹的路径。The GetTempPath method of the System.IO.Path returns the path of the temporary folder.

GetCurrentDirectory方法的System.IO.Directory类返回应用程序的当前正在执行目录。The GetCurrentDirectory method of the System.IO.Directory class returns the application's current executing directory.

RootDirectory属性的DriveInfo类表示指定的驱动器的根目录。The RootDirectory property of the DriveInfo class represents the specified drive's root directory.
存储为应用程序设置的路径Paths stored as application settings 访问相应的应用程序设置属性的包装器类派生自ApplicationSettingsBaseAccess the corresponding applications settings property of the wrapper class derived from ApplicationSettingsBase. 有关详细信息,请参阅应用程序设置为 Windows 窗体For more information, see Application Settings for Windows Forms.
注册表存储Registry storage 某些应用程序在注册表中存储目录信息。Some applications store directory information in the registry. Application类具有CommonAppDataPathLocalUserAppDataPath属性解析为RegistryKey值。The Application class has the CommonAppDataPath and LocalUserAppDataPath properties that resolve to a RegistryKey value.
ClickOnce 应用程序ClickOnce applications 为 ClickOnce 应用程序,使用Application类成员,如UserAppDataPath,这将返回一个指针,ClickOnce 数据目录。For ClickOnce applications, use Application class members such as UserAppDataPath, which will return a pointer to the ClickOnce data directory. 有关详细信息,请参阅访问本地数据和 ClickOnce 应用程序中的远程数据For more information, see Accessing Local and Remote Data in ClickOnce Applications.
国际应用程序International applications 针对国际性应用,相对路径部分从资源中检索字符串在应用程序中使用System.Resources.ResourceReader类。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. 例如,GetFolderPath方法可能用于获取我的文档文件夹的路径,则应用程序设置可以用于添加相对子目录部分。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.

System.IO.Path类包含静态成员,以帮助控制绝对和相对路径字符串,而System.IO.FileSystem.IO.Directory类具有的实际分别处理文件和目录、 静态成员。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.

重要

如果你的应用程序的用户更改中的文件夹FileDialog,则你的应用程序的当前工作目录设置中指定的位置为FileDialogIf 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. 若要防止此情况,设置RestoreDirectory属性设置为trueTo prevent this, set the RestoreDirectory property to true.

字段

EventFileOk EventFileOk EventFileOk EventFileOk

具有 FileOk 事件。Owns the FileOk event.

属性

AddExtension AddExtension AddExtension 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.

AutoUpgradeEnabled AutoUpgradeEnabled AutoUpgradeEnabled AutoUpgradeEnabled

获取或设置一个值,该值指示此 FileDialog 实例在 Windows VistaWindows Vista 上运行时是否应自动升级外观和行为。Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows VistaWindows Vista.

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

获取一个指示组件是否可以引发事件的值。Gets a value indicating whether the component can raise an event.

(Inherited from Component)
CheckFileExists CheckFileExists CheckFileExists 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 CheckPathExists CheckPathExists CheckPathExists

获取或设置一个值,该值指示如果用户指定不存在的路径,对话框是否显示警告。Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.

Container Container Container Container

获取 IContainer,它包含 ComponentGets the IContainer that contains the Component.

(Inherited from Component)
CustomPlaces CustomPlaces CustomPlaces CustomPlaces

获取此 FileDialog 实例的自定义空间的集合。Gets the custom places collection for this FileDialog instance.

DefaultExt DefaultExt DefaultExt DefaultExt

获取或设置默认文件扩展名。Gets or sets the default file name extension.

DereferenceLinks DereferenceLinks DereferenceLinks DereferenceLinks

获取或设置一个值,该值指示对话框是否返回快捷方式引用的文件的位置,或者是否返回快捷方式 (.lnk) 的位置。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 DesignMode DesignMode DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Events Events Events Events

获取附加到此 Component 的事件处理程序的列表。Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
FileName FileName FileName FileName

获取或设置一个包含在文件对话框中选定的文件名的字符串。Gets or sets a string containing the file name selected in the file dialog box.

FileNames FileNames FileNames FileNames

获取对话框中所有选定文件的文件名。Gets the file names of all selected files in the dialog box.

Filter Filter Filter 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 FilterIndex FilterIndex FilterIndex

获取或设置文件对话框中当前选定筛选器的索引。Gets or sets the index of the filter currently selected in the file dialog box.

InitialDirectory InitialDirectory InitialDirectory InitialDirectory

获取或设置文件对话框显示的初始目录。Gets or sets the initial directory displayed by the file dialog box.

Instance Instance Instance Instance

获取应用程序的 Win32 实例句柄。Gets the Win32 instance handle for the application.

Options Options Options Options

获取用来初始化 FileDialog 的值。Gets values to initialize the FileDialog.

RestoreDirectory RestoreDirectory RestoreDirectory RestoreDirectory

获取或设置一个值,该值指示该对话框在关闭前是否将目录还原为之前选定的目录。Gets or sets a value indicating whether the dialog box restores the directory to the previously selected directory before closing.

ShowHelp ShowHelp ShowHelp ShowHelp

获取或设置一个值,该值指示文件对话框中是否显示“帮助”按钮。Gets or sets a value indicating whether the Help button is displayed in the file dialog box.

Site Site Site Site

获取或设置 ComponentISiteGets or sets the ISite of the Component.

(Inherited from Component)
SupportMultiDottedExtensions SupportMultiDottedExtensions SupportMultiDottedExtensions SupportMultiDottedExtensions

获取或设置对话框是否支持显示和保存具有多个文件扩展名的文件。Gets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions.

Tag Tag Tag Tag

获取或设置一个对象,该对象包含控件的数据。Gets or sets an object that contains data about the control.

(Inherited from CommonDialog)
Title Title Title Title

获取或设置文件对话框标题。Gets or sets the file dialog box title.

ValidateNames ValidateNames ValidateNames ValidateNames

获取或设置一个值,该值指示对话框是否只接受有效的 Win32 文件名。Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names.

方法

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) 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() Dispose() Dispose() Dispose()

释放由 Component 使用的所有资源。Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

释放由 Component 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type) GetService(Type) GetService(Type) GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
HookProc(IntPtr, Int32, IntPtr, IntPtr) HookProc(IntPtr, Int32, IntPtr, IntPtr) HookProc(IntPtr, Int32, IntPtr, IntPtr) 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() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
OnFileOk(CancelEventArgs) OnFileOk(CancelEventArgs) OnFileOk(CancelEventArgs) OnFileOk(CancelEventArgs)

引发 FileOk 事件。Raises the FileOk event.

OnHelpRequest(EventArgs) OnHelpRequest(EventArgs) OnHelpRequest(EventArgs) OnHelpRequest(EventArgs)

引发 HelpRequest 事件。Raises the HelpRequest event.

(Inherited from CommonDialog)
OwnerWndProc(IntPtr, Int32, IntPtr, IntPtr) OwnerWndProc(IntPtr, Int32, IntPtr, IntPtr) OwnerWndProc(IntPtr, Int32, IntPtr, IntPtr) 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() Reset() Reset() Reset()

将所有属性重新设置为其默认值。Resets all properties to their default values.

RunDialog(IntPtr) RunDialog(IntPtr) RunDialog(IntPtr) RunDialog(IntPtr)

指定通用对话框。Specifies a common dialog box.

ShowDialog() ShowDialog() ShowDialog() ShowDialog()

用默认的所有者运行通用对话框。Runs a common dialog box with a default owner.

(Inherited from CommonDialog)
ShowDialog(IWin32Window) ShowDialog(IWin32Window) ShowDialog(IWin32Window) ShowDialog(IWin32Window)

运行具有指定所有者的通用对话框。Runs a common dialog box with the specified owner.

(Inherited from CommonDialog)
ToString() ToString() ToString() ToString()

提供此对象的字符串版本。Provides a string version of this object.

事件

Disposed Disposed Disposed Disposed

当通过调用 Dispose() 方法释放组件时发生。Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
FileOk FileOk FileOk FileOk

当用户单击文件对话框中的“打开”或 “保存”按钮时发生。Occurs when the user clicks on the Open or Save button on a file dialog box.

HelpRequest HelpRequest HelpRequest HelpRequest

当用户单击通用对话框中的“帮助”按钮时发生。Occurs when the user clicks the Help button on a common dialog box.

(Inherited from CommonDialog)

适用于

另请参阅