Tutorial: Manipular archivos y directorios en Visual Basic

Este tutorial ofrece una introducción a los fundamentos de la E/S de archivos en Visual Basic.Describe cómo crear una aplicación pequeña que enumera y examina los 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.

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

[!NOTA]

Es posible que su equipo muestre nombres o ubicaciones diferentes para algunos de los elementos de la interfaz de usuario de Visual Studio incluidos en las instrucciones siguientes. La edición de Visual Studio que se tenga y la configuración que se utilice determinan estos elementos. Para obtener más información, vea Valores de configuración de Visual Studio.

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 central Plantillas, 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 agregará el proyecto al Explorador de soluciones y se abrirá el Diseñador de Windows Forms.

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

    Control

    Propiedad.

    Valor

    ListBox

    Name

    filesListBox

    Button

    Name

    Text

    browseButton

    Browse

    Button

    Name

    Text

    examineButton

    Examine

    CheckBox

    Name

    Text

    saveCheckBox

    Guardar resultados

    FolderBrowserDialog

    Name

    FolderBrowserDialog1

Seleccionar una carpeta y enumerar archivos en una carpeta

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

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

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

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

  3. Agregue el siguiente método 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 primero borra el control ListBox.

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

    A continuación, las cadenas que devuelve el método GetFiles se agregan al control ListBox.

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

    ListBox contiene una lista de archivos .txt en la carpeta seleccionada.

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

Obtener atributos de un archivo y contenido de un archivo de texto

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

  2. Agregue el código siguiente al controlador de eventos 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)
    

    El código comprueba que un elemento está seleccionado en ListBox.A continuación, obtiene la entrada de la ruta de acceso del archivo de ListBox.El método FileExists se utiliza para comprobar si el archivo todavía existe.

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

  3. Agregue el siguiente método 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 utiliza el método GetFileInfo para obtener los parámetros del archivo.Los parámetros del archivo se agregan a StringBuilder.

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

  4. Ejecute la aplicación.Haga clic en Browse y vaya a una carpeta que contiene archivos .txt.Haga clic en Aceptar.

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

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

Agregar una entrada de registro

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

    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 del archivo de registro para colocar el archivo de registro en el mismo directorio que el archivo seleccionado.El texto de la entrada de registro se establece en la fecha y hora actual seguido de la información del archivo.

    El método WriteAllText, con el argumento append establecido en True, se utiliza 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 Examine.Compruebe que la entrada de registro está escrita en el archivo log.txt.

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

Utilizar el directorio actual

  1. Haga doble clic en el formulario para crear un controlador de eventos para Form1_Load.

  2. Agregue el siguiente código 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 la carpeta en el directorio actual.

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

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

Habilitar controles de forma selectiva

  1. Agregue el siguiente método SetEnabled.

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

    El método SetEnabled habilita o deshabilita controles dependiendo de si un elemento se selecciona en ListBox.

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

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

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

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

  6. Ejecute la aplicación.La casilla Guardar resultados y el botón Examine se deshabilitan deshabilitados si no se selecciona un elemento en ListBox.

Ejemplo completo utilizando My.Computer.FileSystem

El ejemplo completo aparece a continuación.


    ' 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 utilizando System.IO

El siguiente ejemplo equivalente utiliza las clases del espacio de nombres System.IO en lugar de utilizar los 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

Vea también

Tareas

Tutorial: Manipular archivos utilizando métodos de .NET Framework (Visual Basic)

Referencia

System.IO

FileSystem

CurrentDirectory