Bagikan melalui


Panduan: Memanipulasi File dan Direktori di Visual Basic

Panduan ini memberikan pengenalan tentang dasar-dasar I/O file di Visual Basic. 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 konten pertama. Ada opsi untuk menulis informasi ke file log.

Panduan ini menggunakan anggota 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 System.IO namespace.

Nota

Komputer Anda mungkin menampilkan nama atau lokasi yang berbeda untuk beberapa elemen antarmuka pengguna Visual Studio dalam instruksi berikut. Edisi Visual Studio yang Anda miliki dan pengaturan yang Anda gunakan menentukan elemen-elemen ini. Untuk informasi lebih lanjut, lihat Mempersonalisasi IDE.

Untuk membuat proyek

  1. Pada menu File , klik Proyek Baru.

    Kotak dialog Proyek Baru muncul.

  2. Di panel Templat terinstal , perluas Visual Basic, lalu klik Windows. Di panel Templat 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 Windows Forms Designer terbuka.

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

    Pengendalian Harta benda Nilai
    Kotak Daftar Nama filesListBox
    Tombol Nama

    Teks
    browseButton

    Telusuri
    Tombol Nama

    Teks
    examineButton

    Memeriksa
    Kotak Centang Nama

    Teks
    saveCheckBox

    Simpan Hasil
    FolderBrowserDialog Nama FolderBrowserDialog1

Untuk memilih folder, dan mencantumkan file dalam folder

  1. Buat Click pengendali kejadian untuk browseButton dengan mengklik ganda 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
    

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

  3. Tambahkan metode berikut 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
    

    Kode ini pertama-tama menghapus ListBox.

    Metode ini GetFiles 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 GetFiles metode kemudian ditambahkan ke ListBox.

  4. Jalankan aplikasi. 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 terpilih.

  5. Berhenti menjalankan aplikasi.

Untuk mendapatkan atribut file, dan konten dari file teks

  1. Buat Click pengendali kejadian untuk examineButton dengan mengklik ganda 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 memperoleh entri path file dari ListBox. Metode FileExists ini digunakan untuk memeriksa apakah file masih ada.

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

  3. Tambahkan metode berikut 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
    

    Kode menggunakan GetFileInfo metode untuk mendapatkan parameter file. Parameter dari 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. 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 akhir examineButton_Click penanganan aktivitas.

    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 digunakan untuk membuat entri log, dengan argumen append diatur ke True.

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

  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 pengendali acara.

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

    Kode ini mengatur direktori default browser folder ke direktori saat ini.

  3. Jalankan aplikasi. 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 berikut SetEnabled .

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

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

  2. Buat SelectedIndexChanged penangan peristiwa untuk filesListBox dengan mengklik dua kali kontrol ListBox pada formulir.

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

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

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

  6. Jalankan aplikasi. 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 setara berikut menggunakan kelas dari System.IO namespace alih-alih menggunakan My.Computer.FileSystem objek.


' 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