how to set progress bar during copying file from o

2019-03-03 17:17发布

Currently I'm doing project in vb.net and I want to set the progress bar while copying files from one folder to another. And the progress bar should move towards completion according to amount of file copied.

2条回答
看我几分像从前
2楼-- · 2019-03-03 17:31

Not so new question, but here's an answer nonetheless. The following code will achieve the desired result whereby an individual file's progress is tracked. It uses a 1 MiB buffer. Depending on your system's resources, you can adjust the buffer accordingly to tweak the performance of the transfer.

Concept: Count each byte as it is read/written and report the progress based on the total size of the source file, using file streams.

'Create the file stream for the source file
Dim streamRead as New System.IO.FileStream([sourceFile], System.IO.FileMode.Open)
'Create the file stream for the destination file
Dim streamWrite as New System.IO.FileStream([targetFile], System.IO.FileMode.Create)
'Determine the size in bytes of the source file (-1 as our position starts at 0)
Dim lngLen as Long = streamRead.Length - 1
Dim byteBuffer(1048576) as Byte   'our stream buffer
Dim intBytesRead as Integer    'number of bytes read

While streamRead.Position < lngLen    'keep streaming until EOF
    'Read from the Source
    intBytesRead = (streamRead.Read(byteBuffer, 0, 1048576))
    'Write to the Target
    streamWrite.Write(byteBuffer, 0, intBytesRead)
    'Display the progress
    ProgressBar1.Value = CInt(streamRead.Position / lngLen * 100)
    Application.DoEvents()    'do it
End While

'Clean up 
streamWrite.Flush()
streamWrite.Close()
streamRead.Close()
查看更多
Lonely孤独者°
3楼-- · 2019-03-03 17:54

Concept used: Get the count of files in the source directory, and then whenever copying a file from source folder to destination folder increment a variable to trace how many files get transferred. Now calculate the files transferred percentage by using the following formula,

% of files transferred = How many files Transferred * 100 / Total No of files in source folder

And then after getting the % of files transferred, update the progress bar's value by using it.

Try this code : Tested with IDE

  Dim xNewLocataion = "E:\Test1"

        Dim xFilesCount = Directory.GetFiles("E:\Test").Length
        Dim xFilesTransferred As Integer = 0

        For Each xFiles In Directory.GetFiles("E:\Test")

            File.Copy(xFiles, xNewLocataion & "\" & Path.GetFileName(xFiles), True)
            xFilesTransferred += 1

            ProgressBar1.Value = xFilesTransferred * 100 / xFilesCount
            ProgressBar1.Update()

        Next
查看更多
登录 后发表回答