问题
Trying to create a console application to copy directories from the source to the destination and either the progress bar does nothing while files are copied ...
My.Computer.FileSystem.CopyDirectory(source, destination)
For i = 1 To 100
Console.Write(String.Format("Copy progress: {0}%" & vbCr, i))
Threading.Thread.Sleep(100)
Next
or the progress bar says "Copy Progress 1%" the entire time it's copying ...
For i = 1 To 100
Console.Write(String.Format("Copy progress: {0}%" & vbCr, i))
My.Computer.FileSystem.CopyDirectory(source, destination)
Threading.Thread.Sleep(100)
Next
Wondering what I am doing wrong because I am obviously putting the My.Computer line in the wrong spot!
回答1:
A simple solution, using Linq Select to copy the file list returned by DirectoryInfo.GetFiles()
Pass the sample method an array of Source Directories and a Destination Directory.
The progress (0-100%) is printed to the Output window, and a progress bar gives a visual feedback of the copy status for each Source Path.
This method will return the list of all files copied.
Dim SourcePath As String() = New String() {"[SourcePath1]", "[SourcePath2]", "[SourcePath3]"}
Dim DestinationPath As String = "[DestinationPath]"
Dim FilesCopied As List(Of String) = CopyDirectoryWithProgress(SourcePath, DestinationPath)
Console.ReadLine()
Private Function CopyDirectoryWithProgress(SourcePath() As String, DestPath As String) As List(Of String)
Dim AllFilesCopied As List(Of String) = New List(Of String)
Dim ProgressBarPassSymbol As Char = ChrW(&H25A0)
Dim ProgressBarEmptySymbol As String = New String(ChrW(&H2014), 30)
For Each sPath As String In SourcePath
Dim DirInfo As New DirectoryInfo(sPath)
Dim NumberOfFiles As Integer = Directory.EnumerateFiles(sPath).Count()
Dim ProgressBarPass As Double = (30 / NumberOfFiles)
Dim Increment As Double = 100 / NumberOfFiles
Directory.CreateDirectory(DestPath)
Console.CursorLeft = 0
Console.Write("Copy progress: ")
Console.CursorLeft = 20
Console.Write(ProgressBarEmptySymbol)
AllFilesCopied.AddRange(DirInfo.
GetFiles().
Select(Function(f, i)
File.Copy(Path.Combine(sPath, f.Name), Path.Combine(DestPath, f.Name), True)
Console.CursorLeft = 15
Console.Write("{0:g}% " &
New String(ProgressBarPassSymbol, CInt((i + 1) * ProgressBarPass)),
CInt((i + 1) * Increment))
Return f.FullName
End Function))
Console.WriteLine()
Next
Return AllFilesCopied
End Function
For an interensting method to perform this task with a much faster file enumerator, see this CodeProject article: A Faster Directory Enumerator
回答2:
You can invoke the Windows built-in progress bar when copying using the UIOption.AllDialogs:
My.Computer.FileSystem.CopyFile("C:\text.txt", "C:\my_folder\text.txt", FileIO.UIOption.AllDialogs, FileIO.UICancelOption.DoNothing)
来源:https://stackoverflow.com/questions/50027767/copy-directory-files-with-progress-bar