How can I write a VB.NET program that asynchronously lists all accessible files on all drives of a computer and writes this list to a text file?
How can I write a VB.NET program that asynchronously lists all accessible files on all drives of a computer and writes this list to a text file?
Here is a VB.NET program designed to list all accessible files on all drives and write this list to a file at “c:\filelist.txt“. The code also uses a `BackgroundWorker` to perform the operation asynchronously
Imports System.ComponentModel
Imports System.IO
Imports System.Threading
Imports Microsoft.VisualBasic.Devices
Public Class Form1
Public path As String = "c:\"
Public fileList As New List(Of String)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
_Handles BackgroundWorker1.RunWorkerCompleted
Me.BackColor = Color.Green
End Sub
Sub GetAllAccessibleFiles(path As String, filelist As List(Of String))
For Each file As String In Directory.GetFiles(path, "*.*")
Application.DoEvents()
filelist.Add(file)
Next
For Each dir As String In Directory.GetDirectories(path)
Application.DoEvents()
Try
GetAllAccessibleFiles(dir, filelist)
Catch ex As Exception
' Handle exceptions here if necessary
End Try
Next
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs)
_Handles BackgroundWorker1.DoWork
Application.DoEvents()
For Each drive In DriveInfo.GetDrives
Application.DoEvents()
GetAllAccessibleFiles(drive.ToString, fileList)
Next
Application.DoEvents()
Using sw As New StreamWriter("c:\filelist.txt")
For Each s As String In fileList
Application.DoEvents()
sw.WriteLine(s)
Next
' Flushing and closing StreamWriter
sw.Flush()
sw.Close()
End Using
End Sub
End Class
Related Posts:
Exploring the RB5X: A Journey into the World of Personal Robotics(Opens in a new browser tab)
VB.NET Code to search hard drive in background multi-thread(Opens in a new browser tab)
What are some common types of computer viruses?(Opens in a new browser tab)
What is a virus (computer virus) ?(Opens in a new browser tab)
What is the use of New Keyword in VB.NET?(Opens in a new browser tab)