Instruções passo a passo: manipulando arquivos e diretórios no Visual Basic

Este passo a passo fornece uma introdução para os fundamentos de E/S de arquivo em Visual Basic. Ele descreve como criar um pequeno aplicativo que lista e examina os arquivos de texto em um diretório. Para cada arquivo de texto selecionado, o aplicativo fornece atributos de arquivo e a primeira linha do conteúdo. Há uma opção para gravar as informações em um arquivo de log.

Este passo a passo usa os membros do My.Computer.FileSystem Object, que estão disponíveis no Visual Basic. Consulte FileSystem para obter mais informações. No final do passo a passo, será fornecido um exemplo equivalente que usa classes do namespace System.IO.

Observação

Seu computador pode mostrar diferentes nomes ou locais para alguns dos elementos de interface do usuário do Visual Studio nas instruções a seguir. A edição do Visual Studio que você possui e as configurações que você usa determinam esses elementos. Para obter mais informações, consulte Personalizando o IDE.

Para criar o projeto

  1. No menu Arquivo, clique em Novo Projeto.

    A caixa de diálogo Novo Projeto aparecerá.

  2. No painel Modelos Instalados, expanda Visual Basic e, em seguida, selecione Windows. No meio do painel Modelos, clique em Aplicativo do Windows Forms.

  3. Na caixa Nome, digite FileExplorer para definir o nome do projeto e, em seguida, clique em OK.

    O Visual Studio adiciona o projeto ao Gerenciador de Soluções e o Designer de Formulários do Windows é exibido.

  4. Adicione os controles da tabela a seguir no formulário e defina os valores correspondentes para as respectivas propriedades.

    Control Propriedade Valor
    ListBox Nome filesListBox
    Botão Nome

    Texto
    browseButton

    Procurar
    Botão Nome

    Texto
    examineButton

    Examinar
    CheckBox Nome

    Texto
    saveCheckBox

    Salvar resultados
    FolderBrowserDialog Nome FolderBrowserDialog1

Para selecionar uma pasta e listar arquivos em uma pasta

  1. Criar um manipulador de eventos Click para browseButton, clicando duas vezes no controle no formulário. O Editor de Códigos é aberto.

  2. Adicione o seguinte código ao manipulador de eventos do Click.

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

    A chamada FolderBrowserDialog1.ShowDialog abre a caixa de diálogo Procurar Pasta. Após o usuário clicar em OK, a propriedade SelectedPath será enviada como um argumento para o método ListFiles, que será adicionado na próxima etapa.

  3. Adicione o seguinte 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
    

    Primeiro, esse código limpa a ListBox.

    Depois, o método GetFiles recupera uma coleção de cadeias de caracteres, uma para cada arquivo do diretório. O método GetFiles aceita um argumento de padrão de pesquisa para recuperar os arquivos que correspondem a um padrão específico. Neste exemplo, somente os arquivos que têm a extensão .txt serão retornados.

    As cadeias de caracteres retornadas pelo método GetFiles serão adicionadas à ListBox.

  4. Executar o aplicativo. Clique no botão Procurar . Na caixa de diálogo Procurar Pasta, navegue até uma pasta que contenha os arquivos .txt e, em seguida, selecione a pasta e clique em OK.

    A ListBox contém uma lista de arquivos .txt na pasta selecionada.

  5. Interromper a execução do aplicativo.

Para obter atributos de um arquivo e o conteúdo de um arquivo de texto

  1. Criar um manipulador de eventos Click para examineButton, clicando duas vezes no controle no formulário.

  2. Adicione o seguinte código ao manipulador de eventos do 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)
    

    O código verifica se um item está selecionado na ListBox. Então, ele obtém a entrada de caminho do arquivo da ListBox. O método FileExists é usado para verificar se o arquivo ainda existe.

    O caminho do arquivo será enviado como um argumento para o método GetTextForOutput, que será adicionado na próxima etapa. Esse método retorna uma cadeia de caracteres que contém informações do arquivo. As informações do arquivo aparecem em uma MessageBox.

  3. Adicione o seguinte 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
    

    O código usa o método GetFileInfo para obter parâmetros do arquivo. Os parâmetros do arquivo são adicionados a um StringBuilder.

    O método OpenTextFileReader lê o conteúdo do arquivo em um StreamReader. A primeira linha do conteúdo é obtida de StreamReader e é adicionada no StringBuilder.

  4. Executar o aplicativo. Clique em Procurar e navegue até uma pasta que contenha os arquivos .txt. Clique em OK.

    Selecione um arquivo na ListBox e, em seguida, clique em Examinar. Uma MessageBox mostra as informações do arquivo.

  5. Interromper a execução do aplicativo.

Para adicionar uma entrada de log

  1. Adicione o seguinte código ao final do manipulador de eventos de 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
    

    O código define o caminho do arquivo de log, a fim de colocar o arquivo de log no mesmo diretório que o arquivo selecionado. O texto da entrada de log é definido com a data e hora atuais, seguido pelas informações do arquivo.

    O método WriteAllText, com o argumento append definido como True, é usado para criar a entrada de log.

  2. Executar o aplicativo. Navegue até um arquivo de texto, selecione-o na ListBox, escolha a caixa de seleção Salvar Resultados e, em seguida, clique em Examinar. Verifique se a entrada de log foi gravada para o arquivo log.txt.

  3. Interromper a execução do aplicativo.

Para usar o diretório atual

  1. Crie um manipulador de eventos para Form1_Load, clicando duas vezes no formulário.

  2. Adicione o seguinte código ao manipulador de eventos.

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

    Esse código define o diretório padrão do navegador de pastas para o diretório atual.

  3. Executar o aplicativo. Quando você clica em Procurar pela primeira vez, a caixa de diálogo Procurar Pasta é aberta no diretório atual.

  4. Interromper a execução do aplicativo.

Para habilitar controles de maneira seletiva

  1. Adicione o seguinte método SetEnabled.

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

    O método SetEnabled habilita ou desabilita os controles, dependendo se um item está selecionado na ListBox.

  2. Criar um manipulador de eventos SelectedIndexChanged para filesListBox, clicando duas vezes no controle ListBox no formulário.

  3. Adicione uma chamada para SetEnabled no novo manipulador de eventos filesListBox_SelectedIndexChanged.

  4. Adicione uma chamada para SetEnabled ao final do manipulador de eventos browseButton_Click.

  5. Adicione uma chamada para SetEnabled ao final do manipulador de eventos Form1_Load.

  6. Executar o aplicativo. A caixa de seleção Salvar Resultados e o botão Examinar ficarão desabilitados se um item não for selecionado na ListBox.

Exemplo completo usando My.Computer.FileSystem

A seguir está o exemplo 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

Exemplo completo usando System.IO

O exemplo equivalente a seguir usa classes do namespace System.IO em vez 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

Confira também