Bagikan melalui


Walkthrough: Memanipulasi File dan Direktori di Visual Basic

Panduan ini memberikan pengenalan dasar-dasar I/O file di Visual Basic. Panduan ini menjelaskan cara membuat aplikasi kecil yang mencantumkan dan memeriksa file teks dalam direktori. Untuk setiap file teks yang dipilih, aplikasi menyediakan atribut file dan baris pertama konten. Ada opsi untuk menulis informasi ke file log.

Panduan ini menggunakan anggota dari My.Computer.FileSystem Object, yang tersedia di Visual Basic. Lihat FileSystem untuk informasi lebih lanjut. Di akhir panduan, contoh yang setara disediakan yang menggunakan kelas dari namespace System.IO.

Catatan

Komputer Anda mungkin memperlihatkan nama atau lokasi yang berbeda untuk beberapa elemen antarmuka pengguna Visual Studio dalam petunjuk berikut. Edisi Visual Studio yang Anda miliki dan setelan yang Anda gunakan menentukan elemen-elemen ini. Untuk informasi selengkapnya, lihat Mempersonalisasi IDE.

Untuk membuat proyek

  1. Pada menu File, klik Proyek Baru.

    Kotak dialog Proyek Baru muncul.

  2. Di panel Template Terinstal, luaskan Visual Basic, lalu klik Windows. Di panel Template di tengah, klik Aplikasi Formulir Windows.

  3. Dalam kotak Nama, ketik FileExplorer untuk mengatur nama proyek, lalu klik OK.

    Visual Studio menambahkan proyek ke Penjelajah Solusi, dan Formulir Windows Designer terbuka.

  4. Tambahkan kontrol dalam tabel berikut ke formulir dan atur nilai terkait untuk propertinya.

    Menguasai Properti Nilai
    ListBox Nama filesListBox
    Tombol Nama

    Teks
    browseButton

    People
    Tombol Nama

    Teks
    examineButton

    Periksa
    KotakCentang Nama

    Teks
    saveCheckBox

    Simpan Hasil
    FolderBrowserDialog Nama FolderBrowserDialog1

Untuk memilih folder, dan mencantumkan file dalam folder

  1. Buat penanganan aktivitas Click untuk browseButton dengan mengklik dua kali kontrol pada formulir. Editor Kode terbuka.

  2. Tambahkan kode berikut ke penanganan aktivitas Click.

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

    Panggilan FolderBrowserDialog1.ShowDialog membuka kotak dialog Telusuri Folder. Setelah pengguna mengklik OK, properti SelectedPath dikirim sebagai argumen ke metode ListFiles, yang ditambahkan di langkah berikutnya.

  3. Tambahkan metode ListFiles berikut.

    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
    

    Kode ini pertama-tama menghapus ListBox.

    Metode GetFilesini kemudian mengambil kumpulan string, satu untuk setiap file di direktori. Metode GetFiles menerima argumen pola pencarian untuk mengambil file yang cocok dengan pola tertentu. Dalam contoh ini, hanya file yang memiliki ekstensi .txt yang dikembalikan.

    String yang dikembalikan oleh metode GetFiles kemudian ditambahkan ke ListBox.

  4. Jalankan aplikasi lagi. Klik tombol Telusuri. Dalam kotak dialog Telusuri Folder, telusuri ke folder yang berisi file .txt, lalu pilih folder dan klik OK.

    ListBox berisi daftar file .txt dalam folder yang dipilih.

  5. Berhenti menjalankan aplikasi.

Untuk mendapatkan atribut file, dan konten dari file teks

  1. Buat penanganan aktivitas Click untuk examineButton dengan mengklik dua kali kontrol pada formulir.

  2. Tambahkan kode berikut ke penanganan aktivitas 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)
    

    Kode memverifikasi bahwa item dipilih di ListBox. Kemudian mendapatkan entri jalur file dari ListBox. Metode FileExists ini digunakan untuk memeriksa apakah file masih ada.

    Jalur file dikirim sebagai argumen ke metode GetTextForOutput, yang ditambahkan di langkah berikutnya. Metode ini mengembalikan string yang berisi informasi file. Informasi file muncul di MessageBox.

  3. Tambahkan metode GetTextForOutput berikut.

    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
    

    Kode menggunakan metode GetFileInfo untuk mendapatkan parameter file. Parameter file ditambahkan ke StringBuilder.

    Metode OpenTextFileReader membaca konten file ke dalam StreamReader. Baris pertama konten diperoleh dari StreamReader dan ditambahkan ke StringBuilder.

  4. Jalankan aplikasi lagi. Klik Telusuri, dan telusuri ke folder yang berisi file .txt. Klik OK.

    Pilih file di ListBox, lalu klik Periksa. MessageBox memperlihatkan informasi file.

  5. Berhenti menjalankan aplikasi.

Untuk menambahkan entri log

  1. Tambahkan kode berikut ke ujung penanganan aktivitas 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
    

    Kode mengatur jalur file log untuk menempatkan file log di direktori yang sama dengan file yang dipilih. Teks entri log diatur ke tanggal dan waktu saat ini diikuti oleh informasi file.

    Metode WriteAllText, dengan argumen append diatur ke True, digunakan untuk membuat entri log.

  2. Jalankan aplikasi lagi. Telusuri ke file teks, pilih file itu di ListBox, pilih kotak centang Simpan Hasil, lalu klik Periksa. Verifikasi bahwa entri log ditulis ke file log.txt.

  3. Berhenti menjalankan aplikasi.

Untuk menggunakan direktori saat ini

  1. Buat penanganan aktivitas untuk Form1_Load dengan mengklik dua kali formulir.

  2. Tambahkan kode berikut ke penanganan aktivitas tersebut.

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

    Kode ini mengatur direktori default dari penelusur folder ke direktori saat ini.

  3. Jalankan aplikasi lagi. Saat Anda mengklik Telusuri pertama kali, kotak dialog Telusuri Folder terbuka ke direktori saat ini.

  4. Berhenti menjalankan aplikasi.

Untuk mengaktifkan kontrol secara selektif

  1. Tambahkan metode SetEnabled berikut.

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

    Metode SetEnabled ini mengaktifkan atau menonaktifkan kontrol tergantung pada apakah item dipilih di ListBox.

  2. Buat penanganan aktivitas SelectedIndexChanged untuk filesListBox dengan mengeklik dua kali kontrol ListBox pada formulir.

  3. Tambahkan panggilan ke SetEnabled di penanganan aktivitas filesListBox_SelectedIndexChanged yang baru.

  4. Tambahkan panggilan ke SetEnabled di akhir penanganan aktivitas browseButton_Click.

  5. Tambahkan panggilan ke SetEnabled di akhir penanganan aktivitas Form1_Load.

  6. Jalankan aplikasi lagi. Kotak centang Simpan Hasil dan tombol Periksa dinonaktifkan jika item tidak dipilih di ListBox.

Contoh lengkap menggunakan My.Computer.FileSystem

Berikut ini adalah contoh lengkapnya.


' 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

Contoh lengkap menggunakan System.IO

Contoh yang setara berikut menggunakan kelas dari namespace layanan System.IO alih-alih menggunakan objek 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

Lihat juga