使用进度条复制目录文件

时间:2018-04-25 17:06:46

标签: vb.net progress-bar console-application

尝试创建控制台应用程序以将目录从源复制到目标,并且在复制文件时进度条不执行任何操作...

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

或进度条在复制的整个过程中显示“复制进度1%”...

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

想知道我做错了什么,因为我显然把My.Computer线放在了错误的位置!

2 个答案:

答案 0 :(得分:2)

一个简单的解决方案,使用Linq Select复制DirectoryInfo.GetFiles()返回的文件列表

将示例方法传递给源目录和目标目录的数组 进度(0-100%)将打印到“输出”窗口,进度条会为每个源路径提供复制状态的可视反馈。

此方法将返回复制的所有文件的列表。

enter image description here

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

对于使用更快的文件枚举器执行此任务的interensting方法,请参阅此CodeProject文章:A Faster Directory Enumerator

答案 1 :(得分:1)

使用UIOption.AllDialogs进行复制时,可以调用Windows内置进度条:

My.Computer.FileSystem.CopyFile("C:\text.txt", "C:\my_folder\text.txt", FileIO.UIOption.AllDialogs, FileIO.UICancelOption.DoNothing)