当前位置:网站首页>How to use C WinForm to copy files and display progress
How to use C WinForm to copy files and display progress
2022-07-27 23:51:00 【Yisu cloud】
How do you use it? C# Winform Copy files to show progress
Today, I'd like to share with you how to use C# Winform Realize the relevant knowledge points of copying files and displaying progress , Detailed content , Clear logic , I believe most people still know too much about this knowledge , So share this article for your reference , I hope you will gain something after reading this article , Now let's take a look .
Copying files shows the progress, which is actually the file flow to copy files , And after each piece of file is copied , Use the progress bar to display the copy .
One 、 In this example, we mainly use threads and delegates , In the use of Filestream Class while copying files , Use ProgressBar To display the file copy progress , The key technologies used in this example are explained below .
(1) Thread Constructor
This constructor mainly initializes Thread class . The syntax is as follows :
public Thread(ThreadStart start);
Parameter description :
start:ThreadStart entrust , It represents the method to be called when the thread starts execution .
(2) entrust
Executes the specified delegate on the thread that owns the underlying window handle for this control . The syntax is as follows :
public object Invoke(Delegate method);
Parameter description :
1method: Delegate containing the method to be called in the thread context of the control .
2 Return value : The return value of the delegate being invoked , Or if the delegate does not return a value , Null reference .
Two 、 The following is the design process of the program
(1) stay VS Create a new form application in , And named it FileCopyPlan.
(2) Change the default form Form1 Of Name The attribute is Frm_Main, Add a to the form OpenFileDialog Control is used to select the source file , Add one FolderBrowserDialog Control , Used to select the file save path , Add two TextBox Control , It is used to display the path of source file and destination file respectively , add to 3 individual Button Control , Used to select the path of source file and destination file respectively , And realize the path function of files ; Add one ProgressBar Control is used to display the progress bar .
(3) The background code and comments of the program are as follows :
public partial class Frm_Main : Form { public Frm_Main() { InitializeComponent(); } private System.Threading.Thread thdAddFile; // Create a thread private string str = ""; FileStream FormerOpen;// Instantiation FileStream class FileStream ToFileOpen;// Instantiation FileStream class private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK)// Open the file dialog textBox1.Text = openFileDialog1.FileName;// Get the path to the source file } private void button2_Click(object sender, EventArgs e) { if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)// Open the folders dialog box textBox2.Text = folderBrowserDialog1.SelectedPath;// Get the path to the destination file } private void button3_Click(object sender, EventArgs e) { if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0) { MessageBox.Show(" Please select the original file path or destination file path ."); return; } str = textBox1.Text;// Record the path to the source file str = "\\" + str.Substring(str.LastIndexOf('\\') + 1, str.Length - str.LastIndexOf('\\') - 1);// Get the name of the source file thdAddFile = new Thread(new ThreadStart(SetAddFile));// Create a thread thdAddFile.Start();// Execute the current thread } public delegate void AddFile();// Define the entrusted /// <summary> /// Execute the delegate on the thread /// </summary> public void SetAddFile() { this.Invoke(new AddFile(RunAddFile));// Execute the specified delegate on the thread } /// <summary> /// Copy the file , And close the thread after the copy is complete /// </summary> public void RunAddFile() { CopyFile(textBox1.Text, textBox2.Text + str, 1024, progressBar1);// Copy file thdAddFile.Abort();// Close thread } /// <summary> /// Copy of documents /// </summary> /// <param FormerFile="string"> Source file path </param> /// <param toFile="string"> Destination file path </param> /// <param SectSize="int"> Transfer size </param> /// <param progressBar="ProgressBar">ProgressBar Control </param> public void CopyFile(string FormerFile, string toFile, int SectSize, ProgressBar progressBar1) { progressBar1.Value = 0;// Set the current position of the progress bar to 0 progressBar1.Minimum = 0;// Set the minimum value of the progress bar to 0 FileStream fileToCreate = new FileStream(toFile, FileMode.Create);// Create destination file , If it already exists, it will be overwritten fileToCreate.Close();// Close all resources fileToCreate.Dispose();// Release all resources FormerOpen = new FileStream(FormerFile, FileMode.Open, FileAccess.Read);// Open the source file as read-only ToFileOpen = new FileStream(toFile, FileMode.Append, FileAccess.Write);// Open the destination file in writing int max = Convert.ToInt32(Math.Ceiling((double)FormerOpen.Length / (double)SectSize));// According to the size of a transmission , Calculate the number of transfers progressBar1.Maximum = max;// Set the maximum value of the progress bar int FileSize;// The size of the file to be copied if (SectSize < FormerOpen.Length)// If segmented copy , That is, the content of each copy is less than the total length of the file { byte[] buffer = new byte[SectSize];// According to the size of the transmission , Define an array of bytes int copied = 0;// Record the size of the transfer int tem_n = 1;// Set the number of progress blocks in the progress bar while (copied <= ((int)FormerOpen.Length - SectSize))// Copy body part { FileSize = FormerOpen.Read(buffer, 0, SectSize);// from 0 Start reading , Maximum reading per time SectSize FormerOpen.Flush();// Empty cache ToFileOpen.Write(buffer, 0, SectSize);// Write bytes to the destination file ToFileOpen.Flush();// Empty cache ToFileOpen.Position = FormerOpen.Position;// Make the location of source file and destination file stream the same copied += FileSize;// Record the copied size progressBar1.Value = progressBar1.Value + tem_n;// Add the progress block of the progress bar } int left = (int)FormerOpen.Length - copied;// Get remaining size FileSize = FormerOpen.Read(buffer, 0, left);// Read the remaining bytes FormerOpen.Flush();// Empty cache ToFileOpen.Write(buffer, 0, left);// Write the rest ToFileOpen.Flush();// Empty cache } else// If the whole copy , That is, the content of each copy is greater than the total length of the file { byte[] buffer = new byte[FormerOpen.Length];// Get file size FormerOpen.Read(buffer, 0, (int)FormerOpen.Length);// Read the bytes of the source file FormerOpen.Flush();// Empty cache ToFileOpen.Write(buffer, 0, (int)FormerOpen.Length);// Write and put bytes ToFileOpen.Flush();// Empty cache } FormerOpen.Close();// Release all resources ToFileOpen.Close();// Release all resources if (MessageBox.Show(" Copy complete ") == DialogResult.OK)// Show " Copy complete " Prompt dialog { progressBar1.Value = 0;// Set the current position of the progress bar to 0 textBox1.Clear();// Empty text textBox2.Clear(); str = ""; } } }(4) The running results of the program are shown in the figure :



That's all “ How do you use it? C# Winform Copy files to show progress ” All the content of this article , Thank you for reading ! I believe you will gain a lot after reading this article , Xiaobian will update different knowledge for you every day , If you want to learn more , Please pay attention to the Yisu cloud industry information channel .
边栏推荐
- 数据管理的重点
- js数组复制速度测试220320
- Latex常用总结(2):输入矩阵(输入矩阵、对角阵、方程组等)
- 15million per day! BYD masks won a US $1billion order in California
- 突发,微信重要通知
- CPU的控制方式
- Yijia will release ODM orders in 2020 and make efforts in the middle and low-end market
- Monologue of a software Investor: why don't I pursue fast-growing companies
- Socket interaction process of three handshakes
- 为什么 Redis 集群要使用反向代理? 看这篇就明白了
猜你喜欢

Lua基础语法学习
![[RoarCTF2019]babyRSA威尔逊定理](/img/c1/52e79b6e40390374d48783725311ba.gif)
[RoarCTF2019]babyRSA威尔逊定理

2022夏暑假每日一题(五)

CaEGCN: Cross-Attention Fusion based Enhanced Graph Convolutional Network for Clustering 2021

org.junit.runners.model.InvalidTestClassError: Invalid test class ‘com.zhj.esdemo.MysqlTests‘: 1.

【12月海口】2022年第六届船舶,海洋与海事工程国际会议(NAOME 2022)

用3dmax做折扇的思路方法与步骤

Lua basic grammar learning

Latex常用总结(2):输入矩阵(输入矩阵、对角阵、方程组等)

TCP sticking and unpacking problem + Solution
随机推荐
Can Siemens PLC collect analog data of multiple slave stations in real time and wirelessly?
尚硅谷尚品项目汇笔记(一)
面试官问线程安全的List,看完再也不怕了!
RPA流程自动化机器人是什么技术?如何实现办公自动化?
字符流学习14.3
The first activity of togaf10 standard reading club was successfully held, and the wonderful moments were reviewed!
主数据管理理论与实践
Put cloudflare on the website (take Tencent cloud as an example)
BUUCTF-RSA roll
数据中台的那些“经验与陷阱”
远程调试 idea配置remote debug、在远程服务器的程序中,添加JVM启动参数-Xdebug
[GWCTF 2019]BabyRSA1
Remotely debug idea, configure remote debug, and add JVM startup parameter -xdebug in the program of remote server
New technology leads new changes in marketing of large and medium-sized enterprises, and UFIDA BiP CRM is launched!
四次挥手的Socket交互流程
(十二)51单片机----用DS18B20浅测一下工(江)西的室外温度
proteus仿真arduino中调用DHT11/22温湿度传感器
Your list is too laggy? These four optimizations can make your list silky smooth
MapReduce (III)
MySQL之数据查询(WHERE)