Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
Este passo a passo fornece uma introdução aos conceitos básicos da E/S do arquivo no Visual Basic. Ele descreve como criar um aplicativo pequeno que lista e examina arquivos de texto em um diretório. Para cada arquivo de texto selecionado, o aplicativo fornece atributos de arquivo e a primeira linha de conteúdo. Há uma opção para gravar 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, um exemplo equivalente é fornecido que usa classes do System.IO namespace.
Observação
Seu computador pode mostrar nomes ou locais diferentes 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ê tem e as configurações que você usa determinam esses elementos. Para obter mais informações, consulte Personalizando o IDE.
Para criar o projeto
No menu Arquivo, clique em Novo Projeto.
A caixa de diálogo Novo Projeto aparecerá.
No painel Modelos Instalados , expanda o Visual Basic e clique no Windows. No painel Modelos no meio, clique em Aplicativo do Windows Forms.
Na caixa Nome , digite
FileExplorerpara definir o nome do projeto e clique em OK.O Visual Studio adiciona o projeto ao Gerenciador de Soluções e o Designer de Formulários do Windows é aberto.
Adicione os controles na tabela a seguir ao formulário e defina os valores correspondentes para suas propriedades.
Controle Propriedade Valor ListBox Nome filesListBoxBotão Nome
TextobrowseButton
NavegarBotão Nome
TextoexamineButton
ExaminarCaixa de seleção Nome
TextosaveCheckBox
Salvar ResultadosFolderBrowserDialog Nome FolderBrowserDialog1
Para selecionar uma pasta e listar arquivos em uma pasta
Crie um
Clickmanipulador de eventos parabrowseButtonclicando duas vezes no controle no formulário. O Editor de Código é aberto.Adicione o código a seguir ao manipulador de eventos
Click.If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then ' List files in the folder. ListFiles(FolderBrowserDialog1.SelectedPath) End IfA chamada
FolderBrowserDialog1.ShowDialogabre a caixa de diálogo Procurar Pasta. Depois que o usuário clica em OK, a SelectedPath propriedade é enviada como um argumento para oListFilesmétodo, que é adicionado na próxima etapa.Adicione o método a seguir
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 SubEsse código primeiro limpa o ListBox.
Depois, o método GetFiles recupera uma coleção de cadeias de caracteres, uma para cada arquivo do diretório. O
GetFilesmétodo aceita um argumento de padrão de pesquisa para recuperar arquivos que correspondem a um padrão específico. Neste exemplo, somente os arquivos que têm a extensão .txt são retornados.As cadeias de caracteres retornadas pelo
GetFilesmétodo são adicionadas ao ListBox.Execute o aplicativo. Clique no botão Procurar. Na caixa de diálogo Procurar Pasta , navegue até uma pasta que contém arquivos .txt e selecione a pasta e clique em OK.
O
ListBoxcontém uma lista de arquivos .txt na pasta selecionada.Pare de executar o aplicativo.
Para obter atributos de um arquivo e conteúdo de um arquivo de texto
Crie um
Clickmanipulador de eventos paraexamineButtonclicando duas vezes no controle no formulário.Adicione o código a seguir ao 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 está selecionado no
ListBox. Então, ele obtém a entrada de caminho do arquivo daListBox. O FileExists método é usado para verificar se o arquivo ainda existe.O caminho do arquivo é enviado como um argumento para o
GetTextForOutputmétodo, que é adicionado na próxima etapa. Esse método retorna uma cadeia de caracteres que contém informações de arquivo. As informações do arquivo são exibidas em um MessageBox.Adicione o método a seguir
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 FunctionO código usa o GetFileInfo método para obter parâmetros de arquivo. Os parâmetros de 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 do
StreamReadere é adicionada aoStringBuilder.Execute o aplicativo. Clique em Procurar e navegue até uma pasta que contém arquivos .txt. Clique em OK.
Selecione um arquivo no
ListBox, e então clique em Examinar. UmMessageBoxmostra as informações do arquivo.Pare de executar o aplicativo.
Para adicionar uma entrada de log
Adicione o código a seguir ao final do
examineButton_Clickmanipulador 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 IfO código define o caminho do arquivo de log para colocar o arquivo de log no mesmo diretório que o do arquivo selecionado. O texto da entrada de log é definido como a data e a hora atuais seguidas pelas informações do arquivo.
O WriteAllText método, com o
appendargumento definido comoTrue, é usado para criar a entrada de log.Execute o aplicativo. Navegue até um arquivo de texto, selecione-o
ListBoxna caixa de seleção Salvar Resultados e clique em Examinar. Verifique se a entrada de log está gravada nolog.txtarquivo.Pare de executar o aplicativo.
Para usar o diretório atual
Crie um manipulador de eventos para
Form1_Loadclicando duas vezes no formulário.Adicione o código a seguir ao manipulador de eventos.
' Set the default directory of the folder browser to the current directory. FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectoryEsse código define o diretório padrão do navegador de pastas para o diretório atual.
Execute o aplicativo. Quando você clicar em Procurar na primeira vez, a caixa de diálogo Procurar Pasta será aberta no diretório atual.
Pare de executar o aplicativo.
Para habilitar controles de maneira seletiva
Adicione o método a seguir
SetEnabled.Private Sub SetEnabled() Dim anySelected As Boolean = (filesListBox.SelectedItem IsNot Nothing) examineButton.Enabled = anySelected saveCheckBox.Enabled = anySelected End SubO
SetEnabledmétodo habilita ou desabilita controles dependendo se um item está selecionado noListBox.Crie um
SelectedIndexChangedmanipulador de eventos parafilesListBoxclicando duas vezes no controleListBoxno formulário.Adicione uma chamada a
SetEnabledno novo manipulador de eventosfilesListBox_SelectedIndexChanged.Adicione uma chamada para
SetEnabledno final do manipulador de eventosbrowseButton_Click.Adicione uma chamada para
SetEnabledno final do manipulador de eventosForm1_Load.Execute o aplicativo. A caixa de seleção Salvar Resultados e o botão Examinar serão desabilitados se um item não estiver selecionado no
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 equivalente a seguir usa classes do System.IO namespace 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