Passo a passo: Manipulando arquivos e diretórios em Visual Basic

Esta explicação passo a passo fornece uma introdução para os fundamentos de E/S de arquivos no 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 informações em um arquivo de log.

Esta explicação passo a passo usa membros da My.Computer.FileSystem Object, que estão disponíveis em Visual Basic.Consulte FileSystem para obter mais informações.No final da explicação, é um exemplo equivalente desde que usa as classes da System.IO espaço para nome.

ObservaçãoObservação

Seu computador pode mostrar nomes ou locais diferentes para alguns dos elementos da 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 Configurações de Visual Studio.

Para criar o projeto

  1. No menu File, clique em New Project.

    A caixa de diálogo New Project será exibida.

  2. No Modelos instalados painel, expanda Visual Basice, em seguida, clique em Windows.No modelos de no meio, clique em Painel de Windows Forms Application.

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

    Visual Studio adiciona o projeto para o Solution Explorer e o Windows Forms Designer é aberto.

  4. Adicione os controles na tabela a seguir para o formulário e defina os valores correspondentes para suas propriedades.

    Controle

    Propriedade

    Valor

    ListBox

    Nome

    filesListBox

    Button

    Nome

    Texto

    browseButton

    Browse

    Button

    Nome

    Texto

    examineButton

    Examinar

    CheckBox

    Nome

    Texto

    saveCheckBox

    Salvar resultados

    FolderBrowserDialog

    Nome

    FolderBrowserDialog1

Selecione uma pasta e listar arquivos em uma pasta

  1. Criar um Click manipulador de eventos para browseButton , clicando duas vezes no controle no formulário.Code Editor aparece.

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

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

    O FolderBrowserDialog1.ShowDialog abre de chamar o Procurar pasta caixa de diálogo.Depois que o usuário clica em OK, o SelectedPath propriedade é enviada como um argumento para o ListFiles método, que é adicionado na próxima etapa.

  3. Adicione o seguinte ListFiles método.

    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 primeiro limpa a caixa de listagem.

    O GetFiles método recupera uma coleção de seqüências de caracteres, uma para cada arquivo no diretório.O GetFiles método aceita um argumento de padrão de pesquisa para recuperar arquivos que correspondem a um determinado padrão.Neste exemplo, somente os arquivos que possuem a extensão. txt são retornados.

    Seqüências de caracteres que são retornadas pelo GetFiles método, em seguida, são adicionados para o ListBox.

  4. Execute o aplicativo.Clique no botão Browse.No Procurar pasta caixa de diálogo, navegue até uma pasta que contém os arquivos. txt e, em seguida, selecione a pasta e clique em OK.

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

  5. Pare a execução do aplicativo.

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

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

  2. Adicione o seguinte código para o manipulador 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)
    

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

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

  3. Adicione o seguinte GetTextForOutput método.

    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 a GetFileInfo método para obter os parâmetros de arquivo.Os parâmetros do arquivo são adicionados a um StringBuilder.

    O OpenTextFileReader método lê o conteúdo do arquivo em um StreamReader.A primeira linha do conteúdo é obtida a partir do StreamReader e é adicionado ao StringBuilder.

  4. Execute o aplicativo.Clique em Procurare navegue até uma pasta que contém os arquivos. txt.Clique em OK.

    Selecione um arquivo na ListBoxe, em seguida, clique em Examine.A MessageBox mostra as informações do arquivo.

  5. Pare a execução do aplicativo.

Para adicionar uma entrada de log

  1. Adicione o seguinte código ao final da examineButton_Click manipulador 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
    

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

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

  2. Execute o aplicativo.Vá para um arquivo de texto, selecioná-lo na ListBox, selecione o Salvar resultados caixa de seleção e, em seguida, clique em Examine.Verifique se que a entrada de log é gravada para o log.txt arquivo.

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

    Este código define o diretório padrão do navegador da pasta para a pasta atual.

  3. Execute o aplicativo.Quando você clica em Procurar na primeira vez, o Procurar pasta caixa de diálogo é aberta para o diretório atual.

  4. Pare a execução do aplicativo.

Para ativar seletivamente os controles

  1. Adicione o seguinte SetEnabled método.

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

    O SetEnabled método ativa ou desativa os controles, dependendo se um item é selecionado na ListBox.

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

  3. Adicione uma chamada para SetEnabled nos novos filesListBox_SelectedIndexChanged manipulador de eventos.

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

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

  6. Execute o aplicativo.O Salvar resultados caixa de seleção e o Examine botão está desabilitado se um item não estiver selecionado na ListBox.

Exemplo completo usando My.Computer.FileSystem

Veja a seguir 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 a seguir equivalente usa as classes da System.IO espaço para nome em vez de usar My.Computer.FileSystem objetos.


' 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 também

Tarefas

Passo a passo: Manipulando arquivos usando.NET Framework métodos (Visual Basic)

Referência

System.IO

FileSystem

CurrentDirectory