Tutorial: Manipular archivos y directorios en Visual Basic

En este tutorial se ofrece una introducción a los conceptos básicos de E/S de archivos en Visual Basic. En él se describe cómo crear una pequeña aplicación 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. Existe 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 incluye un ejemplo equivalente que usa clases del espacio de nombres System.IO.

Nota:

Es posible que tu equipo muestre nombres o ubicaciones diferentes para algunos de los elementos de la interfaz de usuario de Visual Studio en las siguientes instrucciones. 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 Personalizar 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 haga clic en Windows. En el panel Plantillas situado en el medio, haga clic en Aplicación de Windows Forms.

  3. En la casilla Nombre, escriba FileExplorer para establecer el nombre del proyecto y, luego, 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 siguiente tabla al formulario y establezca los valores correspondientes para sus propiedades.

    Control Propiedad Value
    ListBox Nombre filesListBox
    Button Nombre

    Texto
    browseButton

    Browse
    Button Nombre

    Texto
    examineButton

    Examine (Examinar)
    CheckBox Nombre

    Texto
    saveCheckBox

    Guardar resultados
    FolderBrowserDialog Nombre FolderBrowserDialog1

Para 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. Después de 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 elimina el elemento ListBox.

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

    Las cadenas devueltas por el método GetFiles se agregan luego al elemento 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 archivos .txt y, luego, selecciónela y haga clic en Aceptar.

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

  5. Deje de ejecutar la aplicación.

Para obtener los 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 hay un elemento seleccionado en ListBox. Después, obtiene la entrada de ruta de archivo de ListBox. El método FileExists se usa para comprobar si el archivo todavía existe.

    La ruta del archivo se envía como argumento al método GetTextForOutput, que se agrega en el paso siguiente. Este método devuelve una cadena que contiene información del archivo. La información del archivo aparece en un elemento 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 usa 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 Examinar y busque una carpeta que contenga archivos .txt. Haga clic en OK.

    Seleccione un archivo en ListBox y, luego, haga clic en Examine (Examinar). La información del archivo se muestra en un MessageBox.

  5. Deje de ejecutar la aplicación.

Para 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 colocarlo en el mismo directorio que el archivo seleccionado. El texto de la entrada de registro se establece en la fecha y 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. Busque un archivo de texto, selecciónelo en ListBox, seleccione la casilla Guardar resultados y, luego, haga clic en Examine (Examinar). Compruebe que la entrada de registro se ha escrito en el archivo log.txt.

  3. Deje de ejecutar 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 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 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. Deje de ejecutar la aplicación.

Para habilitar los 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 los controles dependiendo de si hay un elemento seleccionado 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 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 Examine (Examinar) se deshabilitan si no hay ningún elemento seleccionado en ListBox.

Ejemplo completo usando 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 usando 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

Vea también