Procedura dettagliata: modifica di file e directory in Visual Basic

Questa procedura dettagliata offre un'introduzione ai principi di base degli elementi I/O di file in Visual Basic. Descrive come creare una piccola applicazione in cui vengono elencati ed esaminati i file di testo di una directory. Per ogni file di testo selezionato, l'applicazione specifica gli attributi di file e la prima riga del contenuto. È disponibile un'opzione per la scrittura di informazioni in un file di log.

In questa procedura dettagliata vengono usati i membri di My.Computer.FileSystem Object, che sono disponibili in Visual Basic. Per altre informazioni, vedere FileSystem. Al termine della procedura dettagliata è riportato un esempio equivalente che usa le classi dello spazio dei nomi System.IO.

Nota

I nomi o i percorsi visualizzati per alcuni elementi dell'interfaccia utente di Visual Studio nelle istruzioni seguenti potrebbero essere diversi nel computer in uso. La versione di Visual Studio in uso e le impostazioni configurate determinano questi elementi. Per altre informazioni, vedere Personalizzazione dell'IDE.

Per creare il progetto

  1. Scegliere Nuovo progetto dal menu File.

    Verrà visualizzata la finestra di dialogo Nuovo progetto .

  2. Nel riquadro Modelli installati espandere Visual Basic, quindi fare clic su Windows. Nel riquadro Modelli al centro scegliere Windows Forms Application.

  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 viene aperto Progettazione Windows Form.

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

    Controllo Proprietà valore
    ListBox Nome filesListBox
    Button Nome

    Text
    browseButton

    Sfoglia
    Button Nome

    Text
    examineButton

    Esaminare
    CheckBox Nome

    Text
    saveCheckBox

    Salva risultati
    FolderBrowserDialog Nome FolderBrowserDialog1

Per selezionare una cartella ed elencare file di una cartella

  1. Creare un gestore eventi Click per browseButton facendo doppio clic sul controllo nel form. 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 chiamata a FolderBrowserDialog1.ShowDialog apre la finestra di dialogo Sfoglia per cartelle. Dopo che l'utente ha fatto clic su OK, la proprietà SelectedPath viene inviata come argomento al metodo ListFiles, che viene aggiunto nel passaggio successivo.

  3. Aggiungere il seguente metodo 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 per prima cosa cancella il contenuto dell'oggetto ListBox.

    Il metodo GetFiles recupera quindi una raccolta di stringhe, una per ogni file presente nella directory. Il metodo GetFiles accetta un argomento dei criteri di ricerca per recuperare i file che corrispondono a un criterio specifico. In questo esempio vengono restituiti solo i file con estensione TXT.

    Le stringhe restituite dal metodo GetFiles vengono quindi aggiunte all'oggetto ListBox.

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

    L'oggetto ListBox contiene un elenco di file TXT presenti nella cartella selezionata.

  5. Arrestare l'esecuzione dell'applicazione.

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

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

  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 se un elemento è selezionato nell'oggetto ListBox. Ottiene quindi la voce del percorso del file da ListBox. Il metodo FileExists viene usato per verificare se il file esiste ancora.

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

  3. Aggiungere il seguente metodo 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 metodo GetFileInfo per ottenere i parametri del file. I parametri del file vengono aggiunti a un oggetto StringBuilder.

    Il metodo OpenTextFileReader 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 che contiene file TXT. Fare clic su OK.

    Selezionare un file in ListBox, quindi fare clic su Esaminare. L'oggetto MessageBox contiene le informazioni sul file.

  5. Arrestare l'esecuzione dell'applicazione.

Per aggiungere una voce di log

  1. Aggiungere il codice seguente alla fine del gestore eventi 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
    

    Il codice imposta il percorso del file di log in modo da inserire il file di log nella stessa directory del file selezionato. Il testo della voce di log è impostato su data e ora correnti seguite dalle informazioni sul file.

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

  2. Eseguire l'applicazione. Individuare un file di testo, selezionarlo in ListBox, selezionare la casella di controllo Salva risultati e quindi fare clic su Esaminare. 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 form.

  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 delle cartelle sulla directory corrente.

  3. Eseguire l'applicazione. Quando si fa clic su Sfoglia per la prima volta la finestra di dialogo Sfoglia per cartelle si apre visualizzando la directory corrente.

  4. Arrestare l'esecuzione dell'applicazione.

Per abilitare selettivamente i controlli

  1. Aggiungere il seguente metodo SetEnabled.

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

    Il metodo SetEnabled abilita o disabilita i controlli a seconda se è selezionato un elemento nell'oggetto ListBox.

  2. Creare un gestore eventi SelectedIndexChanged per filesListBox facendo doppio clic sul controllo ListBox nel form.

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

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

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

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

Esempio completo di uso di 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 usando System.IO

Nel seguente esempio equivalente vengono usate le classi dello spazio dei nomi System.IO anziché gli oggetti 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

Vedi anche