当前位置:网站首页>怎么使用C# Winform实现复制文件显示进度
怎么使用C# Winform实现复制文件显示进度
2022-07-27 20:36:00 【亿速云】
怎么使用C# Winform实现复制文件显示进度
今天小编给大家分享一下怎么使用C# Winform实现复制文件显示进度的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
复制文件显示进度实际上就是文件流来复制文件,并在每一块文件复制后,用进度条来显示复制情况。
一、本实例中主要是以线程和委托的方式,在使用Filestream类对文件进行复制的同时,使用ProgressBar来显示文件复制进度,下面对本实例中用到的关键技术进行讲解。
(1) 线程构造函数
该构造函数主要初始化Thread类的新实例。语法格式如下:
public Thread(ThreadStart start);
参数说明:
start:ThreadStart委托,它表示线程开始执行时要调用的方法。
(2) 委托
在拥有此控件的基础窗口句柄的线程上执行指定的委托。语法格式如下:
public object Invoke(Delegate method);
参数说明:
1method:包含要在控件的线程上下文中调用的方法的委托。
2返回值:正在被调用的委托的返回值,或者如果委托没有返回值,则为空引用。
二、下面是程序的设计过程
(1)在VS中新建一个窗体应用程序,并将其命名为FileCopyPlan。
(2)更改默认窗体Form1的Name属性为Frm_Main,在窗体中添加一个OpenFileDialog控件用来选择源文件,添加一个FolderBrowserDialog控件,用来选择文件保存路径,添加两个TextBox控件,分别用来显示源文件和目的文件的路径,添加3个Button控件,分别用来选择源文件和目的文件的路径,以及实现文件的路径功能;添加一个ProgressBar控件用来显示进度条。
(3)程序的后台代码以及注释如下:
public partial class Frm_Main : Form { public Frm_Main() { InitializeComponent(); } private System.Threading.Thread thdAddFile; //创建一个线程 private string str = ""; FileStream FormerOpen;//实例化FileStream类 FileStream ToFileOpen;//实例化FileStream类 private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK)//打开文件对话框 textBox1.Text = openFileDialog1.FileName;//获取源文件的路径 } private void button2_Click(object sender, EventArgs e) { if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)//打开文件夹对话框 textBox2.Text = folderBrowserDialog1.SelectedPath;//获取目的文件的路径 } private void button3_Click(object sender, EventArgs e) { if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0) { MessageBox.Show("请选择原文件路径或目的文件路径。"); return; } str = textBox1.Text;//记录源文件的路径 str = "\\" + str.Substring(str.LastIndexOf('\\') + 1, str.Length - str.LastIndexOf('\\') - 1);//获取源文件的名称 thdAddFile = new Thread(new ThreadStart(SetAddFile));//创建一个线程 thdAddFile.Start();//执行当前线程 } public delegate void AddFile();//定义委托 /// <summary> /// 在线程上执行委托 /// </summary> public void SetAddFile() { this.Invoke(new AddFile(RunAddFile));//在线程上执行指定的委托 } /// <summary> /// 对文件进行复制,并在复制完成后关闭线程 /// </summary> public void RunAddFile() { CopyFile(textBox1.Text, textBox2.Text + str, 1024, progressBar1);//复制文件 thdAddFile.Abort();//关闭线程 } /// <summary> /// 文件的复制 /// </summary> /// <param FormerFile="string">源文件路径</param> /// <param toFile="string">目的文件路径</param> /// <param SectSize="int">传输大小</param> /// <param progressBar="ProgressBar">ProgressBar控件</param> public void CopyFile(string FormerFile, string toFile, int SectSize, ProgressBar progressBar1) { progressBar1.Value = 0;//设置进度栏的当前位置为0 progressBar1.Minimum = 0;//设置进度栏的最小值为0 FileStream fileToCreate = new FileStream(toFile, FileMode.Create);//创建目的文件,如果已存在将被覆盖 fileToCreate.Close();//关闭所有资源 fileToCreate.Dispose();//释放所有资源 FormerOpen = new FileStream(FormerFile, FileMode.Open, FileAccess.Read);//以只读方式打开源文件 ToFileOpen = new FileStream(toFile, FileMode.Append, FileAccess.Write);//以写方式打开目的文件 int max = Convert.ToInt32(Math.Ceiling((double)FormerOpen.Length / (double)SectSize));//根据一次传输的大小,计算传输的个数 progressBar1.Maximum = max;//设置进度栏的最大值 int FileSize;//要拷贝的文件的大小 if (SectSize < FormerOpen.Length)//如果分段拷贝,即每次拷贝内容小于文件总长度 { byte[] buffer = new byte[SectSize];//根据传输的大小,定义一个字节数组 int copied = 0;//记录传输的大小 int tem_n = 1;//设置进度栏中进度块的增加个数 while (copied <= ((int)FormerOpen.Length - SectSize))//拷贝主体部分 { FileSize = FormerOpen.Read(buffer, 0, SectSize);//从0开始读,每次最大读SectSize FormerOpen.Flush();//清空缓存 ToFileOpen.Write(buffer, 0, SectSize);//向目的文件写入字节 ToFileOpen.Flush();//清空缓存 ToFileOpen.Position = FormerOpen.Position;//使源文件和目的文件流的位置相同 copied += FileSize;//记录已拷贝的大小 progressBar1.Value = progressBar1.Value + tem_n;//增加进度栏的进度块 } int left = (int)FormerOpen.Length - copied;//获取剩余大小 FileSize = FormerOpen.Read(buffer, 0, left);//读取剩余的字节 FormerOpen.Flush();//清空缓存 ToFileOpen.Write(buffer, 0, left);//写入剩余的部分 ToFileOpen.Flush();//清空缓存 } else//如果整体拷贝,即每次拷贝内容大于文件总长度 { byte[] buffer = new byte[FormerOpen.Length];//获取文件的大小 FormerOpen.Read(buffer, 0, (int)FormerOpen.Length);//读取源文件的字节 FormerOpen.Flush();//清空缓存 ToFileOpen.Write(buffer, 0, (int)FormerOpen.Length);//写放字节 ToFileOpen.Flush();//清空缓存 } FormerOpen.Close();//释放所有资源 ToFileOpen.Close();//释放所有资源 if (MessageBox.Show("复制完成") == DialogResult.OK)//显示"复制完成"提示对话框 { progressBar1.Value = 0;//设置进度栏的当有位置为0 textBox1.Clear();//清空文本 textBox2.Clear(); str = ""; } } }(4) 程序运行结果如图所示:



以上就是“怎么使用C# Winform实现复制文件显示进度”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。
边栏推荐
- Excel only wants to visualize charts and make data move? Yes, come and watch (with a large number of templates to download)
- 小程序容器技术超有料,可以让移动研发效率大幅提升
- Basic SQL general syntax and classification
- Basic lighting of unity
- WWW 2019 | HAN:异质图注意力网络
- Summary of exam on May 17, 2022
- 8000 word explanation of OBSA principle and application practice
- 简单实用的数据可视化案例
- Security-001
- Simple and practical data visualization cases
猜你喜欢

Dry goods semantic web, Web3.0, Web3, metauniverse, these concepts are still confused? (medium)

Preliminary understanding of Panda3D audio and advanced interactive components

LANproxy mapping local development environment

【GNN报告】加拿大蒙特利尔唐建:Geometric Deep Learning For Drug Discovery
![[GNN report] Tang Jian, Montreal, Canada: Geometric deep learning for drug discovery](/img/ef/aa490aeff5a0690257cd6eca7d5e28.png)
[GNN report] Tang Jian, Montreal, Canada: Geometric deep learning for drug discovery

机器学习项目可视化展示方法

Cy3 fluorescent labeling antibody / protein Kit (10~100mg labeling amount)

微信安装包11年膨胀575倍,UP主:“98%的文件是垃圾”;苹果应用商店被曝大量色情App;四大科技巨头呼吁废除闰秒|极客头条

初步了解Panda3D音频和高级交互组件

The principle and demonstration of service path lifting without quotation marks
随机推荐
Library management system based on SSM framework
Gstore weekly gstore source code analysis (V): log tracking of security mechanism
Do you want to be dismissed? Let's take a look at the "exit tips" of programmers
迪赛智慧数——其他图表(平行坐标图):家庭未来资产配置意愿
Pyqt5 rapid development and practice 4.10 window drawing controls
一篇文章读懂人工神经网络
The prefix is not removed when zuul gateway automatically routes
Deploy dolphin scheduler high availability cluster based on rainbow
营收、利润两位数增长,华润怡宝悄悄打造了这些过亿新品
containerd ctr运行ansible容器执行ansible-playbook任务完整命令
【数字识别】基于知识库实现手写体数字识别附matlab代码
怎么使用xshell免费版
Cy3 fluorescent labeling antibody / protein Kit (10~100mg labeling amount)
小程序容器技术超有料,可以让移动研发效率大幅提升
Pro multi store version system, versatile is it!
What is the b+tree index of MySQL? How does the cluster index grow?
The principle and demonstration of service path lifting without quotation marks
4 轮拿下字节 Offer,面试题复盘
Pentium fast system call learning
Interviewer: I can't carry a backpack at all. Are you going by yourself or I'll give you a lift?