C#根据文件大小显示文件复制进度条
作者:野牛程序员:2023-12-28 20:02:42C#阅读 3070
使用C#编写程序时,可以使用System.IO命名空间中的FileInfo类来获取文件的大小,然后结合其他UI组件来显示文件复制的进度条。
下面是一个简单的示例代码,演示如何在C# WinForms应用程序中根据文件大小显示文件复制的进度条。请确保你的WinForms项目中包含了一个ProgressBar控件(例如,命名为progressBar1)和一个Button控件(例如,命名为startButton)。
using System;
using System.IO;
using System.Windows.Forms;
using System.Threading.Tasks;
namespace FileCopyApp
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
// 设置按钮点击事件
startButton.Click += StartButton_Click;
}
private async void StartButton_Click(object sender, EventArgs e)
{
// 显示文件选择对话框以获取源文件路径
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string sourceFilePath = openFileDialog.FileName;
// 显示文件保存对话框以获取目标文件路径
SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string destinationFilePath = saveFileDialog.FileName;
// 使用异步任务复制文件,并更新进度条
await CopyFileWithProgressAsync(sourceFilePath, destinationFilePath);
MessageBox.Show("文件复制完成!");
}
}
}
private async Task CopyFileWithProgressAsync(string sourceFilePath, string destinationFilePath)
{
// 获取源文件大小
FileInfo fileInfo = new FileInfo(sourceFilePath);
long totalBytes = fileInfo.Length;
// 初始化进度条
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = 0;
using (FileStream sourceStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
using (FileStream destinationStream = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write))
{
byte[] buffer = new byte[4096]; // 调整缓冲区大小,根据需要调整
int bytesRead;
long totalBytesRead = 0;
while ((bytesRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await destinationStream.WriteAsync(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
// 计算进度百分比
int progressPercentage = (int)((double)totalBytesRead / totalBytes * 100);
// 更新进度条
UpdateProgressBar(progressPercentage);
}
}
}
private void UpdateProgressBar(int value)
{
// 在UI线程上更新进度条
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke(new Action<int>(UpdateProgressBar), value);
}
else
{
progressBar1.Value = value;
}
}
}
}这个示例使用了异步编程,确保文件复制不会阻塞主线程,同时更新进度条。在CopyFileWithProgressAsync方法中,通过await关键字进行异步读取和写入文件,并通过UpdateProgressBar方法在UI线程上更新进度条。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

