例如,假设您要复制文件 "source.txt" 到 "destination.txt",可以使用以下代码:
Private Sub btnCopy_Click(sender As Object, e As EventArgs) Handles btnCopy.Click
Dim sourceFile As String = "source.txt"
Dim destinationFile As String = "destination.txt"
CopyFileWithProgress(sourceFile, destinationFile, ProgressBar1)
End Sub
创建一个名为 CopyFileWithProgress 的函数,该函数将复制文件并更新进度条。
Private Sub CopyFileWithProgress(ByVal sourceFile As String, ByVal destinationFile As String, ByVal progressBar As ProgressBar)
Dim fileSize As Long = New FileInfo(sourceFile).Length
Using sourceStream As New FileStream(sourceFile, FileMode.Open)
Using destinationStream As New FileStream(destinationFile, FileMode.Create)
Dim buffer(4096) As Byte
Dim totalBytesCopied As Long = 0
Dim bytesCopied As Integer
bytesCopied = sourceStream.Read(buffer, 0, buffer.Length)
destinationStream.Write(buffer, 0, bytesCopied)
totalBytesCopied += bytesCopied
Dim percentage As Integer = CInt((totalBytesCopied / fileSize) * 100)
progressBar.Value = percentage
Application.DoEvents()
Loop While bytesCopied > 0
End Using
End Using
End Sub
这个函数中,我们首先获取源文件大小,然后创建源和目标文件流。在循环中,我们从源文件读取和复制数据到目标文件,并更新进度条。在每次更新进度条后,我们需要调用 Application.DoEvents() 方法以确保 UI 可以及时更新。
这样,当您点击按钮时,进度条将显示文件复制的进度,并在完成时停止。