Condividi tramite


Procedura dettagliata: Modifica di file e directory in Visual Basic

Questa procedura dettagliata fornisce un'introduzione ai concetti fondamentali dell'I/O dei file in Visual Basic. Descrive come creare una piccola applicazione che elenca ed esamina i file di testo in una directory. Per ogni file di testo selezionato, l'applicazione fornisce attributi di file e la prima riga di contenuto. È possibile scrivere informazioni in un file di log.

Questa procedura dettagliata usa i membri di My.Computer.FileSystem Object, disponibili in Visual Basic. Per altre informazioni, vedere FileSystem. Alla fine della procedura dettagliata viene fornito un esempio che utilizza classi equivalenti dello spazio dei nomi System.IO.

Annotazioni

Il computer potrebbe visualizzare nomi o percorsi diversi per alcuni degli elementi dell'interfaccia utente di Visual Studio nelle istruzioni seguenti. L'edizione di Visual Studio disponibile e le impostazioni usate determinano questi elementi. Per altre informazioni, vedere Personalizzazione dell'IDE.

Per creare il progetto

  1. Nel menu File fare clic su Nuovo progetto.

    Verrà visualizzata la finestra di dialogo Nuovo progetto.

  2. Nel riquadro Modelli installati espandere Visual Basic e quindi fare clic su Windows. Nel riquadro Modelli al centro fare clic su Applicazione Windows Form.

  3. Nella casella Nome digitare FileExplorer per impostare il nome del progetto e quindi fare clic su OK.

    Visual Studio aggiunge il progetto a Esplora soluzioni e apre il Designer Windows Forms.

  4. Aggiungere i controlli nella tabella seguente al form e impostare i valori corrispondenti per le relative proprietà.

    Controllo Proprietà Valore
    ListBox Nome filesListBox
    pulsante Nome

    Testo
    browseButton

    Esplora
    pulsante Nome

    Testo
    examineButton

    Esaminare
    CheckBox Nome

    Testo
    saveCheckBox

    Salva risultati
    FolderBrowserDialog Nome FolderBrowserDialog1

Per selezionare una cartella ed elencare i file in una cartella

  1. Creare un Click gestore eventi per browseButton facendo doppio clic sul controllo nel modulo. Verrà aperto l'editor di codice.

  2. Aggiungere il codice seguente al gestore eventi Click.

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

    La FolderBrowserDialog1.ShowDialog chiamata apre la finestra di dialogo Sfoglia cartella . Dopo che l'utente fa clic su OK, la SelectedPath proprietà viene inviata come argomento al ListFiles metodo , che viene aggiunto nel passaggio successivo.

  3. Aggiungere il metodo seguente 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
    

    Questo codice cancella innanzitutto listBox.

    Il GetFiles metodo recupera quindi una raccolta di stringhe, una per ogni file nella directory. Il metodo GetFiles accetta un argomento del pattern di ricerca per ottenere i file che corrispondono a un pattern specifico. In questo esempio vengono restituiti solo i file con estensione .txt.

    Le stringhe restituite dal GetFiles metodo vengono quindi aggiunte a ListBox.

  4. Eseguire l'applicazione. Fare clic sul pulsante Sfoglia. Nella finestra di dialogo Sfoglia cartella passare a una cartella contenente .txt file, quindi selezionare la cartella e fare clic su OK.

    ListBox Contiene un elenco di file .txt nella cartella selezionata.

  5. Arrestare l'esecuzione dell'applicazione.

Per ottenere gli attributi di un file e il contenuto da un file di testo

  1. Creare un Click gestore eventi per examineButton facendo doppio clic sul controllo nel modulo.

  2. Aggiungere il codice seguente al gestore eventi 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)
    

    Il codice verifica che un elemento sia selezionato in ListBox. Successivamente, ottiene il percorso del file dall'oggetto ListBox. Il FileExists metodo viene usato per verificare se il file esiste ancora.

    Il percorso del file viene inviato come argomento al GetTextForOutput metodo , che viene aggiunto nel passaggio successivo. Questo metodo restituisce una stringa contenente informazioni sul file. Le informazioni sul file sono visualizzate in un MessageBox.

  3. Aggiungere il metodo seguente 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
    

    Il codice usa il GetFileInfo metodo per ottenere i parametri di file. I parametri del file vengono aggiunti a un oggetto StringBuilder.

    Il OpenTextFileReader metodo legge il contenuto del file in un oggetto StreamReader. La prima riga del contenuto viene ottenuta da StreamReader e viene aggiunta a StringBuilder.

  4. Eseguire l'applicazione. Fare clic su Sfoglia e passare a una cartella contenente .txt file. Fare clic su OK.

    Selezionare un file in ListBoxe quindi fare clic su Esamina. MessageBox mostra le informazioni sul file.

  5. Arrestare l'esecuzione dell'applicazione.

Per aggiungere una voce di log

  1. Aggiungere il codice seguente alla fine del examineButton_Click gestore eventi.

    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
    

    Il codice imposta il percorso del file di log per inserire il file di log nella stessa directory del file selezionato. Il testo della voce di log viene impostato sulla data e l'ora correnti seguite dalle informazioni sul file.

    Il WriteAllText metodo , con l'argomento append impostato su True, viene usato per creare la voce di log.

  2. Eseguire l'applicazione. Passare a un file di testo, selezionarlo in ListBox, selezionare la casella di controllo Salva risultati e quindi fare clic su Esamina. Verificare che la voce di log sia scritta nel file log.txt.

  3. Arrestare l'esecuzione dell'applicazione.

Per usare la directory corrente

  1. Creare un gestore eventi per Form1_Load facendo doppio clic sul modulo.

  2. Aggiungere il codice seguente al gestore eventi.

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

    Questo codice imposta la directory predefinita del browser di cartelle sulla directory corrente.

  3. Eseguire l'applicazione. Quando si fa clic su Sfoglia per la prima volta, viene visualizzata la finestra di dialogo Sfoglia cartella nella directory corrente.

  4. Arrestare l'esecuzione dell'applicazione.

Per abilitare in modo selettivo i controlli

  1. Aggiungere il metodo seguente SetEnabled .

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

    Il SetEnabled metodo abilita o disabilita i controlli a seconda che un elemento sia selezionato in ListBox.

  2. Creare un SelectedIndexChanged gestore eventi per filesListBox effettuando un doppio clic sul controllo ListBox nel modulo.

  3. Aggiungere una chiamata a SetEnabled nel nuovo filesListBox_SelectedIndexChanged gestore eventi.

  4. Inserisci una chiamata a SetEnabled alla fine del gestore di eventi browseButton_Click.

  5. Inserisci una chiamata a SetEnabled alla fine del gestore di eventi Form1_Load.

  6. Eseguire l'applicazione. La casella di controllo Salva risultati e il pulsante Esamina sono disabilitati se un elemento non è selezionato in ListBox.

Esempio completo con My.Computer.FileSystem

Di seguito è riportato l'esempio 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

Esempio completo con System.IO

Nell'esempio equivalente seguente vengono utilizzate classi dello System.IO spazio dei nomi anziché usare My.Computer.FileSystem oggetti .


' 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

Vedere anche