Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.NET Framework Class Library
FileDialog Class

Updated: October 2010

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
Public MustInherit Class FileDialog _
    Inherits CommonDialog
C#
public abstract class FileDialog : CommonDialog
Visual C++
public ref class FileDialog abstract : public CommonDialog
F#
[<AbstractClass>]
type FileDialog =  
    class
        inherit CommonDialog
    end

The FileDialog type exposes the following members.

  NameDescription
Public propertyAddExtensionGets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.
Public propertyAutoUpgradeEnabledGets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows Vista.
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event. (Inherited from Component.)
Public propertyCheckFileExistsGets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.
Public propertyCheckPathExistsGets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.
Public propertyContainerGets the IContainer that contains the Component. (Inherited from Component.)
Public propertyCustomPlacesGets the custom places collection for this FileDialog instance.
Public propertyDefaultExtGets or sets the default file name extension.
Public propertyDereferenceLinksGets 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).
Protected propertyDesignModeGets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Protected propertyEventsGets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public propertyFileNameGets or sets a string containing the file name selected in the file dialog box.
Public propertyFileNamesGets the file names of all selected files in the dialog box.
Public propertyFilterGets 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.
Public propertyFilterIndexGets or sets the index of the filter currently selected in the file dialog box.
Public propertyInitialDirectoryGets or sets the initial directory displayed by the file dialog box.
Protected propertyInstanceInfrastructure. Gets the Win32 instance handle for the application.
Protected propertyOptionsInfrastructure. Gets values to initialize the FileDialog.
Public propertyRestoreDirectoryGets or sets a value indicating whether the dialog box restores the current directory before closing.
Public propertyShowHelpGets or sets a value indicating whether the Help button is displayed in the file dialog box.
Public propertySiteGets or sets the ISite of the Component. (Inherited from Component.)
Public propertySupportMultiDottedExtensionsGets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions.
Public propertyTagGets or sets an object that contains data about the control. (Inherited from CommonDialog.)
Public propertyTitleGets or sets the file dialog box title.
Public propertyValidateNamesGets or sets a value indicating whether the dialog box accepts only valid Win32 file names.
Top
  NameDescription
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodDispose()()()Releases all resources used by the Component. (Inherited from Component.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Inherited from Component.)
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeReleases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodGetServiceReturns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodHookProcDefines the common dialog box hook procedure that is overridden to add specific functionality to the file dialog box. (Overrides CommonDialog..::.HookProc(IntPtr, Int32, IntPtr, IntPtr).)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodMemberwiseClone()()()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected methodOnFileOkRaises the FileOk event.
Protected methodOnHelpRequestRaises the HelpRequest event. (Inherited from CommonDialog.)
Protected methodOwnerWndProcDefines the owner window procedure that is overridden to add specific functionality to a common dialog box. (Inherited from CommonDialog.)
Public methodResetResets all properties to their default values. (Overrides CommonDialog..::.Reset()()().)
Protected methodRunDialogInfrastructure. Specifies a common dialog box. (Overrides CommonDialog..::.RunDialog(IntPtr).)
Public methodShowDialog()()()Runs a common dialog box with a default owner. (Inherited from CommonDialog.)
Public methodShowDialog(IWin32Window)Runs a common dialog box with the specified owner. (Inherited from CommonDialog.)
Public methodToStringInfrastructure. Provides a string version of this object. (Overrides Component..::.ToString()()().)
Top
  NameDescription
Public eventDisposedOccurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public eventFileOkOccurs when the user clicks on the Open or Save button on a file dialog box.
Public eventHelpRequestOccurs when the user clicks the Help button on a common dialog box. (Inherited from CommonDialog.)
Top
  NameDescription
Protected fieldStatic memberEventFileOkInfrastructure. Owns the FileOk event.
Top

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 noteCaution

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

Important noteImportant

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.

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

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Date

History

Reason

October 2010

Added link to FolderBrowserDialog.

Customer feedback.

Biblioteca de clases de .NET Framework
FileDialog (Clase)

Muestra un cuadro de diálogo en el que el usuario puede seleccionar un archivo.

Espacio de nombres:  System.Windows.Forms
Ensamblado:  System.Windows.Forms (en System.Windows.Forms.dll)
Visual Basic
Public MustInherit Class FileDialog _
    Inherits CommonDialog
C#
public abstract class FileDialog : CommonDialog
Visual C++
public ref class FileDialog abstract : public CommonDialog
F#
[<AbstractClass>]
type FileDialog =  
    class
        inherit CommonDialog
    end

El tipo FileDialog expone los siguientes miembros.

  NombreDescripción
Propiedad públicaAddExtensionObtiene o establece un valor que indica si el cuadro de diálogo agrega automáticamente una extensión a un nombre de archivo en caso de que el usuario omita dicha extensión.
Propiedad públicaAutoUpgradeEnabledObtiene o establece un valor que indica si esta instancia de FileDialog debe actualizar automáticamente el aspecto y el comportamiento cuando se ejecute en Windows Vista.
Propiedad protegidaCanRaiseEventsObtiene un valor que indica si el componente puede generar un evento. (Se hereda de Component).
Propiedad públicaCheckFileExistsObtiene o establece un valor que indica si el cuadro de diálogo muestra una advertencia cuando el usuario especifica un nombre de archivo que no existe.
Propiedad públicaCheckPathExistsObtiene o establece un valor que indica si el cuadro de diálogo muestra una advertencia cuando el usuario especifica una ruta de acceso que no existe.
Propiedad públicaContainerObtiene IContainer que contiene Component. (Se hereda de Component).
Propiedad públicaCustomPlacesObtiene la colección de ubicaciones personalizadas de esta instancia de FileDialog.
Propiedad públicaDefaultExtObtiene o establece la extensión de nombre de archivo predeterminada.
Propiedad públicaDereferenceLinksObtiene o establece un valor que indica si el cuadro de diálogo devuelve la ubicación del archivo al que hace referencia el acceso directo o bien devuelve la ubicación del acceso directo (.lnk).
Propiedad protegidaDesignModeObtiene un valor que indica si Component está actualmente en modo de diseño. (Se hereda de Component).
Propiedad protegidaEventsObtiene la lista de controladores de eventos asociados a Component. (Se hereda de Component).
Propiedad públicaFileNameObtiene o establece una cadena que contiene el nombre de archivo seleccionado en el cuadro de diálogo de archivo.
Propiedad públicaFileNamesObtiene los nombres de todos los archivos seleccionados en el cuadro de diálogo.
Propiedad públicaFilterObtiene o establece la cadena actual de filtro de nombres de archivo, que determina las opciones que aparecen en los cuadros "Guardar como archivo de tipo" o "Archivos de tipo" del cuadro de diálogo.
Propiedad públicaFilterIndexObtiene o establece el índice del filtro actualmente seleccionado en el cuadro de diálogo de archivo.
Propiedad públicaInitialDirectoryObtiene o establece el directorio inicial que muestra el cuadro de diálogo de archivo.
Propiedad protegidaInstanceInfraestructura. Obtiene el identificador de instancia Win32 de la aplicación.
Propiedad protegidaOptionsInfraestructura. Obtiene los valores para inicializar el objeto FileDialog.
Propiedad públicaRestoreDirectoryObtiene o establece un valor que indica si el cuadro de diálogo restaura el directorio actual antes de cerrarse.
Propiedad públicaShowHelpObtiene o establece un valor que indica si se muestra el botón Ayuda en el cuadro de diálogo de archivo.
Propiedad públicaSiteObtiene o establece ISite de Component. (Se hereda de Component).
Propiedad públicaSupportMultiDottedExtensionsObtiene o establece si el cuadro de diálogo admite mostrar y guardar archivos que tienen varias extensiones de nombre de archivo.
Propiedad públicaTagObtiene o establece un objeto que contiene datos sobre el control . (Se hereda de CommonDialog).
Propiedad públicaTitleObtiene o establece el título del cuadro de diálogo de archivo.
Propiedad públicaValidateNamesObtiene o establece un valor que indica si el cuadro de diálogo acepta sólo nombres de archivo Win32 válidos.
Arriba
  NombreDescripción
Método públicoCreateObjRefCrea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto. (Se hereda de MarshalByRefObject).
Método públicoDispose()()()Libera todos los recursos utilizados por el objeto Component. (Se hereda de Component).
Método protegidoDispose(Boolean)Libera los recursos no administrados usados por Component y, opcionalmente, los recursos administrados. (Se hereda de Component).
Método públicoEquals(Object)Determina si el objeto Object especificado es igual al objeto Object actual. (Se hereda de Object).
Método protegidoFinalizeLibera recursos no administrados y realiza otras operaciones de limpieza antes de que se reclame el objeto Component durante la recolección de elementos no utilizados. (Se hereda de Component).
Método públicoGetHashCodeActúa como función hash para un tipo concreto. (Se hereda de Object).
Método públicoGetLifetimeServiceRecupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia. (Se hereda de MarshalByRefObject).
Método protegidoGetServiceDevuelve un objeto que representa el servicio suministrado por Component o por Container. (Se hereda de Component).
Método públicoGetTypeObtiene el objeto Type de la instancia actual. (Se hereda de Object).
Método protegidoHookProcDefine el procedimiento de enlace para cuadros de diálogo comunes que se reemplaza para agregar una funcionalidad específica a un cuadro de diálogo de archivo. (Invalida a CommonDialog..::.HookProc(IntPtr, Int32, IntPtr, IntPtr)).
Método públicoInitializeLifetimeServiceObtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia. (Se hereda de MarshalByRefObject).
Método protegidoMemberwiseClone()()()Crea una copia superficial del objeto Object actual. (Se hereda de Object).
Método protegidoMemberwiseClone(Boolean)Crea una copia superficial del objeto MarshalByRefObject actual. (Se hereda de MarshalByRefObject).
Método protegidoOnFileOkDesencadena el evento FileOk.
Método protegidoOnHelpRequestProvoca el evento HelpRequest. (Se hereda de CommonDialog).
Método protegidoOwnerWndProcDefine el procedimiento de ventana propietaria que se reemplaza para agregar una funcionalidad específica a un cuadro de diálogo común. (Se hereda de CommonDialog).
Método públicoResetRestablece los valores predeterminados de todas las propiedades. (Invalida a CommonDialog..::.Reset()()()).
Método protegidoRunDialogInfraestructura. Especifica un cuadro de diálogo común. (Invalida a CommonDialog..::.RunDialog(IntPtr)).
Método públicoShowDialog()()()Ejecuta un cuadro de diálogo común con un propietario predeterminado. (Se hereda de CommonDialog).
Método públicoShowDialog(IWin32Window)Ejecuta un cuadro de diálogo común con el propietario especificado. (Se hereda de CommonDialog).
Método públicoToStringInfraestructura. Devuelve una versión de cadena de este objeto . (Invalida a Component..::.ToString()()()).
Arriba
  NombreDescripción
Evento públicoDisposedSe produce cuando el componente se elimina mediante una llamada al método Dispose. (Se hereda de Component).
Evento públicoFileOkSe desencadena cuando el usuario hace clic en el botón Abrir o Guardar de un cuadro de diálogo de archivo.
Evento públicoHelpRequestSe produce cuando el usuario hace clic en el botón Ayuda en un cuadro de diálogo común. (Se hereda de CommonDialog).
Arriba
  NombreDescripción
Campo protegidoMiembro estáticoEventFileOkInfraestructura. Contiene el evento FileOk.
Arriba

La clase FileDialog es una clase abstracta que contiene las funciones comunes de las clases OpenFileDialog y SaveFileDialog. Esta clase no se ha diseñado para que se utilice directamente, sino para que contenga el funcionamiento común de estas dos clases. No se puede crear una instancia de FileDialog. Aunque la clase se declara como pública, no se puede heredar de ella, dado que contiene métodos abstractos internos. Para crear un cuadro de diálogo en el que el usuario pueda seleccionar o guardar un archivo, utilice OpenFileDialog o SaveFileDialog.

FileDialog es un cuadro de diálogo modal; por lo tanto, al mostrarse, bloquea el resto de la aplicación hasta que el usuario haya elegido un archivo. Al mostrar un cuadro de diálogo en forma modal, es posible que no se produzca ninguna entrada de datos (mediante teclado o con el mouse), salvo en los objetos del propio cuadro de diálogo. El programa debe ocultar o cerrar el cuadro de diálogo (normalmente, en respuesta a alguna acción del usuario) antes de admitir la entrada de datos en el programa de llamada.

Nota de precauciónPrecaución

Cuando utilice clases derivadas de FileDialog, como OpenFileDialog y SaveFileDialog, evite utilizar literales de cadena que contengan rutas de acceso absolutas. En su lugar, obtenga dinámicamente la ruta de acceso utilizando una o varias de las técnicas descritas en la tabla siguiente.

Si desea permitir a los usuarios seleccionar una carpeta en lugar de un archivo, utilice FolderBrowserDialog.

En función del tipo de aplicación, del modo en que los datos asociados a la aplicación están almacenados y del motivo de acceso al sistema de archivos, existen numerosos mecanismos posibles para crear una ruta de acceso a un directorio. En la tabla siguiente se muestran las técnicas para crear dinámicamente rutas de acceso.

Ruta de acceso o categoría de programa

Clase y miembros que se van a utilizar

Rutas de acceso estándar de Windows, como Archivos de programa, Mis documentos, Escritorio, etc.

La clase System..::.Environment es el origen más completo de estos elementos, ya sea a través de sus métodos estáticos, como SystemDirectory, o a través del método GetFolderPath, que utiliza uno de los valores enumerados de Environment..::.SpecialFolder.

Rutas de acceso relativas a la aplicación actual

La clase Application tiene miembros estáticos que van a obtener ciertas rutas de acceso, como StartupPath, ExecutablePath, LocalUserAppDataPath y CommonAppDataPath.

El método GetTempPath de la clase System.IO..::.Path devuelve la ruta de acceso de la carpeta temporal.

El método GetCurrentDirectory de la clase System.IO..::.Directory devuelve el directorio en ejecución actual de la aplicación.

La propiedad RootDirectory de la clase DriveInfo representa el directorio raíz de la unidad especificada.

Rutas de acceso almacenadas como valores de la aplicación

Obtiene acceso a la propiedad de configuración de aplicaciones correspondiente de la clase contenedora derivada de ApplicationSettingsBase. Para obtener más información, vea Configuración de la aplicación en formularios Windows Forms.

Almacenamiento del Registro

Algunas aplicaciones almacenan información de los directorios en el Registro. La clase Application tiene las propiedades CommonAppDataPath y LocalUserAppDataPath que se resuelven como un valor RegistryKey.

Aplicaciones ClickOnce

En las aplicaciones ClickOnce, utilice los miembros de clase Application, como UserAppDataPath, que devolverá un puntero al directorio de datos ClickOnce. Para obtener más información, vea Obtener acceso local o remoto a los datos en aplicaciones ClickOnce.

Aplicaciones internacionales

En las aplicaciones internacionales, recupere la parte de la ruta de acceso relativa de un recurso de cadena de la aplicación mediante la clase System.Resources..::.ResourceReader. Para obtener más información sobre globalización y localización, vea el tema Codificación y localización.

Tenga en cuenta que una ruta de acceso completa se puede crear utilizando una o varias de las técnicas descritas. Por ejemplo, el método GetFolderPath se podría utilizar para obtener la ruta de acceso a la carpeta Mis documentos, y un valor de la aplicación se podría utilizar para agregar una parte del subdirectorio correspondiente.

La clase System.IO..::.Path contiene miembros estáticos que facilitan la manipulación de cadenas de ruta de acceso absolutas y relativas, mientras que las clases System.IO..::.File y System.IO..::.Directory tienen miembros estáticos que en realidad manipulan archivos y directorios, respectivamente.

Nota importanteImportante

Si el usuario de la aplicación cambia la carpeta de FileDialog el directorio de trabajo actual para la aplicación se establece en la ubicación especificada en FileDialog. Para evitarlo, establezca la propiedad RestoreDirectory en true.

En el siguiente ejemplo se utiliza la implementación OpenFileDialog de FileDialog y se ilustra la creación, el establecimiento de propiedades y la presentación del cuadro de diálogo. En el ejemplo se utiliza el método ShowDialog para mostrar el cuadro de diálogo y devolver DialogResult. En el ejemplo se requiere un formulario con un objeto Button colocado en él y el espacio de nombres System.IO agregado al mismo.

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

.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Fecha

Historial

Motivo

Octubre de 2010

Agregado vínculo a FolderBrowserDialog.

Comentarios de los clientes.

Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker