vb.net 如何对文件夹实现复制,并显示进度条,每复制一个文件还在richtextbox1中显示出来!
利用线程,和计时器,Function GetFolderSize从网上借鉴的,不知道为什么IO类不支持不同分区移动,所以移动目录只能在相同分区,设计界面如图,代码如下
Imports System.Threading
Imports System.IO
Imports System.Text
Public Class Form1
Dim SourceDir, DestDir As String
Dim SourceLen As Integer
'返回文件夹大小
Private Function GetFolderSize(ByVal DirPath As String, Optional ByVal IncludeSubFolders As Boolean = True) As Long
Dim lngDirSize As Long
Dim objFileInfo As FileInfo
Dim objDir As DirectoryInfo = New DirectoryInfo(DirPath)
Dim objSubFolder As DirectoryInfo
Try
For Each objFileInfo In objDir.GetFiles()
lngDirSize += objFileInfo.Length
Next
If IncludeSubFolders Then
For Each objSubFolder In objDir.GetDirectories()
凳拍 高侍lngDirSize += GetFolderSize(objSubFolder.FullName)
Next
End If
Catch
End Try
Return lngDirSize
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim T As New Thread(AddressOf DirMove)
CheckForIllegalCrossThreadCalls = False
SourceDir = TextBox1.Text
DestDir = TextBox2.Text
SourceLen = GetFolderSize(SourceDir)
ProgressBar1.Value = 0
Timer1.Interval = 100
Timer1.Start()
T.Start()
枣念羡End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If Directory.Exists(DestDir) = False Then Exit Sub
ProgressBar1.Value = Math.Round(GetFolderSize(DestDir) / SourceLen, 2) * 100
End Sub
Private Sub DirMove()
Me.Text = "正在移动..."
Directory.Move(SourceDir, DestDir)
Me.Text = "移动完成!"
ProgressBar1.Value = 100
RichTextBox1.Text += DestDir & Environment.NewLine
End Sub
End Class