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
继承
派生

示例

下面的代码示例使用OpenFileDialogFileDialog实现, 并说明了如何创建、设置属性和显示对话框。The following code example uses the OpenFileDialog implementation of FileDialog and illustrates creating, setting of properties, and showing the dialog box. 该示例使用ShowDialog方法来显示对话框, 并DialogResult返回。The 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. 不能创建的FileDialog实例。You cannot create an instance of FileDialog. 尽管类是公开的, 但您不能从它继承, 因为它包含内部抽象方法。Although the class is declared public, you cannot inherit from it, as it contains internal abstract methods. 若要创建对话框以选择或保存文件, 请使用OpenFileDialog或。 SaveFileDialogTo 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类 ( OpenFileDialog如和SaveFileDialog) 时, 请避免使用包含绝对路径的字符串。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 路径, 如程序文件、MyDocuments、桌面等Standard Windows paths, such as Program Files, MyDocuments, the Desktop and so on 类是它们的最完整源, 无论是通过其静态方法SystemDirectory(如), 还是通过GetFolderPath方法使用Environment.SpecialFolder枚举值之一。 System.EnvironmentThe 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 ExecutablePath StartupPath CommonAppDataPath LocalUserAppDataPath类具有静态成员, 用于获取特定路径, 例如、、和。 ApplicationThe 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.

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

DriveInfoRootDirectory的属性表示指定驱动器的根目录。The RootDirectory property of the DriveInfo class represents the specified drive's root directory.
存储为应用程序设置的路径Paths stored as application settings 访问从ApplicationSettingsBase派生的包装器类的相应应用程序设置属性。Access 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. 类具有解析LocalUserAppDataPath为值RegistryKey的和属性。 CommonAppDataPath ApplicationThe 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可以使用方法获取 MyDocuments 文件夹的路径, 然后可以使用应用程序设置来添加相对子目录部分。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.File System.IO.Directory类则分别具有实际操作文件和目录的静态成员。 System.IO.PathThe 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中的文件夹, 则你的应用程序的当前工作目录将设置为FileDialog中指定的位置。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. 若要防止出现这种RestoreDirectory情况, true请将属性设置为。To 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)

适用于

另请参阅