Compartir a través de


Tutorial: Manipular archivos y directorios en Visual Basic

En este tutorial se proporciona una introducción a los aspectos básicos de la E/S de archivos en Visual Basic. Describe cómo crear una aplicación pequeña que enumera y examina archivos de texto en un directorio. Para cada archivo de texto seleccionado, la aplicación proporciona atributos de archivo y la primera línea de contenido. Hay una opción para escribir información en un archivo de registro.

En este tutorial se usan los miembros del elemento My.Computer.FileSystem Object, que están disponibles en Visual Basic. Consulte FileSystem para obtener más información. Al final del tutorial, se proporciona un ejemplo equivalente que usa clases del System.IO espacio de nombres.

Nota:

El equipo puede mostrar nombres o ubicaciones diferentes para algunos de los elementos de la interfaz de usuario de Visual Studio en las instrucciones siguientes. La edición de Visual Studio que tiene y la configuración que usa determinan estos elementos. Para obtener más información, consulte Personalizando el IDE.

Para crear el proyecto

  1. En el menú Archivo , haga clic en Nuevo proyecto.

    Aparecerá el cuadro de diálogo Nuevo proyecto .

  2. En el panel Plantillas instaladas , expanda Visual Basic y, a continuación, haga clic en Windows. En el panel Plantillas situado en el medio, haga clic en Aplicación de Windows Forms.

  3. En el cuadro Nombre , escriba FileExplorer para establecer el nombre del proyecto y, a continuación, haga clic en Aceptar.

    Visual Studio agrega el proyecto al Explorador de soluciones y se abre el Diseñador de Windows Forms.

  4. Agregue los controles de la tabla siguiente al formulario y establezca los valores correspondientes para sus propiedades.

    Supervisión Propiedad Importancia
    ListBox Nombre filesListBox
    Botón Nombre

    Texto
    browseButton

    Navegar
    Botón Nombre

    Texto
    examineButton

    Examinar
    CheckBox Nombre

    Texto
    saveCheckBox

    Guardar resultados
    FolderBrowserDialog Nombre FolderBrowserDialog1

Para seleccionar una carpeta y enumerar los archivos de una carpeta

  1. Cree un Click controlador de eventos para browseButton haciendo doble clic en el control del formulario. Se abre el Editor de código.

  2. Agregue el código siguiente al controlador de Click eventos.

    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
    End If
    

    La FolderBrowserDialog1.ShowDialog llamada abre el cuadro de diálogo Buscar carpeta . Después de que el usuario haga clic en Aceptar, la SelectedPath propiedad se envía como argumento al ListFiles método , que se agrega en el paso siguiente.

  3. Agregue el método siguiente ListFiles .

    Private Sub ListFiles(ByVal folderPath As String)
        filesListBox.Items.Clear()
    
        Dim fileNames = My.Computer.FileSystem.GetFiles(
            folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
    
        For Each fileName As String In fileNames
            filesListBox.Items.Add(fileName)
        Next
    End Sub
    

    Este código borra primero listBox.

    A continuación, el GetFiles método recupera una colección de cadenas, una para cada archivo del directorio. El GetFiles método acepta un argumento de patrón de búsqueda para recuperar archivos que coinciden con un patrón determinado. En este ejemplo, solo se devuelven los archivos que tienen la extensión .txt.

    Las cadenas devueltas por el GetFiles método se agregan a ListBox.

  4. Ejecute la aplicación. Haga clic en el botón Examinar . En el cuadro de diálogo Buscar carpeta , busque una carpeta que contenga .txt archivos y, a continuación, seleccione la carpeta y haga clic en Aceptar.

    El ListBox contiene una lista de archivos .txt dentro de la carpeta seleccionada.

  5. Detenga la ejecución de la aplicación.

Para obtener atributos de un archivo y contenido de un archivo de texto

  1. Cree un Click controlador de eventos para examineButton haciendo doble clic en el control del formulario.

  2. Agregue el código siguiente al controlador de Click eventos.

    If filesListBox.SelectedItem Is Nothing Then
        MessageBox.Show("Please select a file.")
        Exit Sub
    End If
    
    ' Obtain the file path from the list box selection.
    Dim filePath = filesListBox.SelectedItem.ToString
    
    ' Verify that the file was not removed since the
    ' Browse button was clicked.
    If My.Computer.FileSystem.FileExists(filePath) = False Then
        MessageBox.Show("File Not Found: " & filePath)
        Exit Sub
    End If
    
    ' Obtain file information in a string.
    Dim fileInfoText As String = GetTextForOutput(filePath)
    
    ' Show the file information.
    MessageBox.Show(fileInfoText)
    

    El código verifica que se haya seleccionado un elemento en ListBox. Después, obtiene la entrada de ruta de archivo de ListBox. El FileExists método se usa para comprobar si el archivo sigue existiendo.

    La ruta de acceso del archivo se envía como argumento al método GetTextForOutput, que se añade en el paso siguiente. Este método devuelve una cadena que contiene información de archivo. La información del archivo aparece en un cuadro de mensajes.

  3. Agregue el método siguiente GetTextForOutput .

    Private Function GetTextForOutput(ByVal filePath As String) As String
        ' Verify that the file exists.
        If My.Computer.FileSystem.FileExists(filePath) = False Then
            Throw New Exception("File Not Found: " & filePath)
        End If
    
        ' Create a new StringBuilder, which is used
        ' to efficiently build strings.
        Dim sb As New System.Text.StringBuilder()
    
        ' Obtain file information.
        Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)
    
        ' Add file attributes.
        sb.Append("File: " & thisFile.FullName)
        sb.Append(vbCrLf)
        sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
        sb.Append(vbCrLf)
        sb.Append("Size: " & thisFile.Length.ToString & " bytes")
        sb.Append(vbCrLf)
    
        ' Open the text file.
        Dim sr As System.IO.StreamReader =
            My.Computer.FileSystem.OpenTextFileReader(filePath)
    
        ' Add the first line from the file.
        If sr.Peek() >= 0 Then
            sb.Append("First Line: " & sr.ReadLine())
        End If
        sr.Close()
    
        Return sb.ToString
    End Function
    

    El código usa el GetFileInfo método para obtener parámetros de archivo. Los parámetros de archivo se agregan a un StringBuilder.

    El OpenTextFileReader método lee el contenido del archivo en un StreamReader. La primera línea del contenido se obtiene de StreamReader y se agrega a la StringBuilder.

  4. Ejecute la aplicación. Haga clic en Examinar y vaya a una carpeta que contenga .txt archivos. Haz clic en Aceptar.

    Seleccione un archivo en y, a continuación, haga clic en ListBoxExaminar. MessageBox muestra la información del archivo.

  5. Detenga la ejecución de la aplicación.

Para agregar una entrada de registro

  1. Agregue el código siguiente al final del examineButton_Click controlador de eventos.

    If saveCheckBox.Checked = True Then
        ' Place the log file in the same folder as the examined file.
        Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
        Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")
    
        Dim logText As String = "Logged: " & Date.Now.ToString &
            vbCrLf & fileInfoText & vbCrLf & vbCrLf
    
        ' Append text to the log file.
        My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
    End If
    

    El código establece la ruta de acceso del archivo de registro para colocar el archivo de registro en el mismo directorio que el del archivo seleccionado. El texto de la entrada del registro se establece con la fecha y la hora actuales, seguido de la información del archivo.

    El método WriteAllText, con el argumento append establecido en True, se usa para crear la entrada de registro.

  2. Ejecute la aplicación. Vaya a un archivo de texto, selecciónelo en ListBox, active la casilla Guardar resultados y, a continuación, haga clic en Examinar. Compruebe que la entrada de registro se escribe en el log.txt archivo.

  3. Detenga la ejecución de la aplicación.

Para usar el directorio actual

  1. Cree un controlador de eventos para Form1_Load haciendo doble clic en el formulario.

  2. Agregue el código siguiente al controlador de eventos.

    ' Set the default directory of the folder browser to the current directory.
    FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory
    

    Este código establece el directorio predeterminado del explorador de carpetas en el directorio actual.

  3. Ejecute la aplicación. Al hacer clic en Examinar la primera vez, se abre el cuadro de diálogo Buscar carpeta en el directorio actual.

  4. Detenga la ejecución de la aplicación.

Para habilitar de forma selectiva los controles

  1. Agregue el método siguiente SetEnabled .

    Private Sub SetEnabled()
        Dim anySelected As Boolean =
            (filesListBox.SelectedItem IsNot Nothing)
    
        examineButton.Enabled = anySelected
        saveCheckBox.Enabled = anySelected
    End Sub
    

    El SetEnabled método habilita o deshabilita los controles en función de si se selecciona un elemento en .ListBox

  2. Cree un SelectedIndexChanged controlador de eventos para filesListBox haciendo doble clic en el control ListBox en el formulario.

  3. Agregue una llamada a SetEnabled en el nuevo filesListBox_SelectedIndexChanged controlador de eventos.

  4. Agregue una llamada a SetEnabled al final del controlador de eventos browseButton_Click.

  5. Agregue una llamada a SetEnabled al final del controlador de eventos Form1_Load.

  6. Ejecute la aplicación. La casilla Guardar resultados y el botón Examinar están deshabilitados si un elemento no está seleccionado en .ListBox

Ejemplo completo con My.Computer.FileSystem

A continuación se muestra el ejemplo completo.


' This example uses members of the My.Computer.FileSystem
' object, which are available in Visual Basic.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Set the default directory of the folder browser to the current directory.
    FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory

    SetEnabled()
End Sub

Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
    End If
    SetEnabled()
End Sub

Private Sub ListFiles(ByVal folderPath As String)
    filesListBox.Items.Clear()

    Dim fileNames = My.Computer.FileSystem.GetFiles(
        folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")

    For Each fileName As String In fileNames
        filesListBox.Items.Add(fileName)
    Next
End Sub

Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
    If filesListBox.SelectedItem Is Nothing Then
        MessageBox.Show("Please select a file.")
        Exit Sub
    End If

    ' Obtain the file path from the list box selection.
    Dim filePath = filesListBox.SelectedItem.ToString

    ' Verify that the file was not removed since the
    ' Browse button was clicked.
    If My.Computer.FileSystem.FileExists(filePath) = False Then
        MessageBox.Show("File Not Found: " & filePath)
        Exit Sub
    End If

    ' Obtain file information in a string.
    Dim fileInfoText As String = GetTextForOutput(filePath)

    ' Show the file information.
    MessageBox.Show(fileInfoText)

    If saveCheckBox.Checked = True Then
        ' Place the log file in the same folder as the examined file.
        Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
        Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")

        Dim logText As String = "Logged: " & Date.Now.ToString &
            vbCrLf & fileInfoText & vbCrLf & vbCrLf

        ' Append text to the log file.
        My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
    End If
End Sub

Private Function GetTextForOutput(ByVal filePath As String) As String
    ' Verify that the file exists.
    If My.Computer.FileSystem.FileExists(filePath) = False Then
        Throw New Exception("File Not Found: " & filePath)
    End If

    ' Create a new StringBuilder, which is used
    ' to efficiently build strings.
    Dim sb As New System.Text.StringBuilder()

    ' Obtain file information.
    Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)

    ' Add file attributes.
    sb.Append("File: " & thisFile.FullName)
    sb.Append(vbCrLf)
    sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
    sb.Append(vbCrLf)
    sb.Append("Size: " & thisFile.Length.ToString & " bytes")
    sb.Append(vbCrLf)

    ' Open the text file.
    Dim sr As System.IO.StreamReader =
        My.Computer.FileSystem.OpenTextFileReader(filePath)

    ' Add the first line from the file.
    If sr.Peek() >= 0 Then
        sb.Append("First Line: " & sr.ReadLine())
    End If
    sr.Close()

    Return sb.ToString
End Function

Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
    SetEnabled()
End Sub

Private Sub SetEnabled()
    Dim anySelected As Boolean =
        (filesListBox.SelectedItem IsNot Nothing)

    examineButton.Enabled = anySelected
    saveCheckBox.Enabled = anySelected
End Sub

Ejemplo completo con System.IO

En el siguiente ejemplo equivalente se usan clases del espacio de nombres System.IO en lugar de usar objetos My.Computer.FileSystem.


' This example uses classes from the System.IO namespace.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Set the default directory of the folder browser to the current directory.
    FolderBrowserDialog1.SelectedPath =
        System.IO.Directory.GetCurrentDirectory()

    SetEnabled()
End Sub

Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
        SetEnabled()
    End If
End Sub

Private Sub ListFiles(ByVal folderPath As String)
    filesListBox.Items.Clear()

    Dim fileNames As String() =
        System.IO.Directory.GetFiles(folderPath,
            "*.txt", System.IO.SearchOption.TopDirectoryOnly)

    For Each fileName As String In fileNames
        filesListBox.Items.Add(fileName)
    Next
End Sub

Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
    If filesListBox.SelectedItem Is Nothing Then
        MessageBox.Show("Please select a file.")
        Exit Sub
    End If

    ' Obtain the file path from the list box selection.
    Dim filePath = filesListBox.SelectedItem.ToString

    ' Verify that the file was not removed since the
    ' Browse button was clicked.
    If System.IO.File.Exists(filePath) = False Then
        MessageBox.Show("File Not Found: " & filePath)
        Exit Sub
    End If

    ' Obtain file information in a string.
    Dim fileInfoText As String = GetTextForOutput(filePath)

    ' Show the file information.
    MessageBox.Show(fileInfoText)

    If saveCheckBox.Checked = True Then
        ' Place the log file in the same folder as the examined file.
        Dim logFolder As String =
            System.IO.Path.GetDirectoryName(filePath)
        Dim logFilePath = System.IO.Path.Combine(logFolder, "log.txt")

        ' Append text to the log file.
        Dim logText As String = "Logged: " & Date.Now.ToString &
            vbCrLf & fileInfoText & vbCrLf & vbCrLf

        System.IO.File.AppendAllText(logFilePath, logText)
    End If
End Sub

Private Function GetTextForOutput(ByVal filePath As String) As String
    ' Verify that the file exists.
    If System.IO.File.Exists(filePath) = False Then
        Throw New Exception("File Not Found: " & filePath)
    End If

    ' Create a new StringBuilder, which is used
    ' to efficiently build strings.
    Dim sb As New System.Text.StringBuilder()

    ' Obtain file information.
    Dim thisFile As New System.IO.FileInfo(filePath)

    ' Add file attributes.
    sb.Append("File: " & thisFile.FullName)
    sb.Append(vbCrLf)
    sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
    sb.Append(vbCrLf)
    sb.Append("Size: " & thisFile.Length.ToString & " bytes")
    sb.Append(vbCrLf)

    ' Open the text file.
    Dim sr As System.IO.StreamReader =
        System.IO.File.OpenText(filePath)

    ' Add the first line from the file.
    If sr.Peek() >= 0 Then
        sb.Append("First Line: " & sr.ReadLine())
    End If
    sr.Close()

    Return sb.ToString
End Function

Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
    SetEnabled()
End Sub

Private Sub SetEnabled()
    Dim anySelected As Boolean =
        (filesListBox.SelectedItem IsNot Nothing)

    examineButton.Enabled = anySelected
    saveCheckBox.Enabled = anySelected
End Sub

Consulte también