Procedura dettagliata: modifica di file e directory in Visual Basic

In questa procedura dettagliata viene fornita un'introduzione ai principi fondamentali relativi a I/O di file in Visual Basic.Viene descritto come creare un'applicazione di piccole dimensioni che consente di elencare ed esaminare i file di testo in una directory.Per ogni file di testo selezionato, l'applicazione fornisce i relativi attributi e la prima riga di contenuto.È disponibile un'opzione per scrivere le informazioni in un file di log.

In questa procedura dettagliata vengono utilizzati membri di My.Computer.FileSystem Object disponibili in Visual Basic.Per ulteriori informazioni, vedere FileSystem.Alla fine della procedura dettagliata viene fornito un esempio equivalente in cui vengono utilizzate le classi dello spazio dei nomi System.IO.

[!NOTA]

Nel computer in uso è possibile che vengano visualizzati nomi o percorsi diversi per alcuni elementi dell'interfaccia utente di Visual Studio nelle istruzioni seguenti. La versione di Visual Studio in uso e le impostazioni configurate determinano questi elementi. Per ulteriori informazioni vedere Impostazioni di Visual Studio.

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.Al centro del riquadro Modelli fare clic su Applicazione Windows Form.

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

    Il progetto verrà aggiunto a Esplora soluzioni in Visual Studio e verrà avviato Progettazione Windows Form.

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

    Controllo

    Proprietà

    Valore

    ListBox

    Nome

    filesListBox

    Button

    Nome

    Text

    browseButton

    Sfoglia

    Button

    Nome

    Text

    examineButton

    Examine

    CheckBox

    Nome

    Text

    saveCheckBox

    Save Results

    FolderBrowserDialog

    Nome

    FolderBrowserDialog1

Per selezionare una cartella ed elencare i file in 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 di FolderBrowserDialog1.ShowDialog consente di visualizzare la finestra di dialogo Sfoglia per cartelle.Una volta che si è 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 dapprima consente di cancellare ListBox.

    Il metodo GetFiles consente quindi di recuperare una raccolta di stringhe, una per ogni file nella directory.Il metodo GetFiles accetta un argomento del criterio di ricerca per recuperare i file che corrispondono a un modello particolare.Nell'esempio riportato di seguito vengono restituiti solo i file con estensione txt.

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

  4. Eseguire l'applicazione.Scegliere il pulsante Browse.Nella finestra di dialogo Sfoglia per cartelle cercare una cartella contenente i file txt, quindi selezionare la cartella e fare clic su OK.

    Il controllo ListBox contiene un elenco di file txt della 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 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 che un elemento venga selezionato nel controllo ListBox.Ottiene quindi la voce del percorso del file dal controllo ListBox.Il metodo FileExists viene utilizzato per controllare 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 contenente le informazioni sul file.Le informazioni sul file vengono visualizzate in 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 utilizza il metodo GetFileInfo per ottenere i parametri del file.I parametri del file vengono aggiunti a StringBuilder.

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

  4. Eseguire l'applicazione.Fare clic su Sfoglia e cercare una cartella contenente i file txt.Scegliere OK.

    Selezionare un file nel controllo ListBox, quindi fare clic su Esamina.MessageBox consente di visualizzare le informazioni sul file.

  5. Arrestare l'esecuzione dell'applicazione.

Per aggiungere una voce di log

  1. Aggiungere il seguente codice 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 per inserire il file di log nella stessa directory del file selezionato.Il testo della voce di log viene impostato sulla data e ora correnti seguiti dalle informazioni sul file.

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

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

  3. Arrestare l'esecuzione dell'applicazione.

Per utilizzare la directory corrente

  1. Creare un gestore di 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 consente di impostare la directory predefinita del visualizzatore 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 per cartelle con la directory corrente.

  4. Arrestare l'esecuzione dell'applicazione.

Per abilitare in modo selettivo 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 un elemento è selezionato in 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 Esamina sono disattivati se un elemento non è selezionato in ListBox.

Esempio completo di utilizzo di My.Computer.FileSystem

Di seguito è riportato un 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 di utilizzo di System.IO

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


' 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

Attività

Procedura dettagliata: modifica di file mediante i metodi .NET Framework (Visual Basic)

Riferimenti

System.IO

FileSystem

CurrentDirectory