如何在vb.net中将文件从一个文件夹复制到另一个文件夹时设置进度条? [英] how to set progress bar during copying file from one folder to another in vb.net?

查看:613
本文介绍了如何在vb.net中将文件从一个文件夹复制到另一个文件夹时设置进度条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我在vb.net做项目,我想设置进度条,同时将文件从一个文件夹复制到另一个。

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.

推荐答案

不是这么新的问题,但这里是一个答案。以下代码将实现所需的结果,从而跟踪单个文件的进度。它使用1 MiB缓冲区。

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()

这篇关于如何在vb.net中将文件从一个文件夹复制到另一个文件夹时设置进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆