当前位置:网站首页>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 .
边栏推荐
- Under the epidemic, TSMC's growth in the first quarter exceeded expectations, with 7Nm accounting for 35%! Second quarter or record high
- Introduction to several common usage scenarios of message queue
- Reduce error demonstration
- Interviewer: let's talk about the specific process of network data transmission
- MySQL data query (where)
- RPA流程自动化机器人是什么技术?如何实现办公自动化?
- The first activity of togaf10 standard reading club was successfully held, and the wonderful moments were reviewed!
- Apple releases new iPhone se: equipped with A13 bionic processor, priced from 3299 yuan
- What are the methods of process synchronization?
- NB-IoT产业的现状与未来:跨过1亿出货门槛,奔向5G大连接!
猜你喜欢

Character stream learning 14.3

Bank marketing predicts the success rate of a customer's purchase of financial products
![[RoarCTF2019]RSA](/img/0e/8c8371ccf40094e5b03e502d6ae851.png)
[RoarCTF2019]RSA
![[NCTF2019]babyRSA1](/img/c1/52e79b6e40390374d48783725311ba.gif)
[NCTF2019]babyRSA1

J9数字科普:Sui网络的双共识是如何工作的?

Can Siemens PLC collect analog data of multiple slave stations in real time and wirelessly?

NDK 系列(6):说一下注册 JNI 函数的方式和时机

proteus仿真arduino中调用DHT11/22温湿度传感器

如果我们是那晚负责修复 B 站崩了的开发人员

详解分布式系统的幂等
随机推荐
Common Taylor expansion
Unity 实现简单画板画画功能(笔记)
BUUCTF-bbbbbbrsa
给网站套上Cloudflare(以腾讯云为例)
并发和并行有什么区别?
为什么需要等待计时2MSL?
Ideas, methods and steps of making folding fans with 3DMAX
JS提升:JS中的数组扁平化问题
三次握手的Socket交互流程
Lua基础语法学习
尚硅谷尚品项目汇笔记(一)
What is the prospect of low code development? Are you really optimistic about low code development?
TOGAF10标准读书会首场活动圆满举办,精彩时刻回顾!
TCP sticking and unpacking problem + Solution
用3dmax做折扇的思路方法与步骤
Accelerate IGBT localization! BYD semiconductor will be listed independently, with a market value of 30billion yuan!
Redis的分布式锁
基于mediapipe的姿态识别和简单行为识别
【C语言】通讯录(动态版本)
2019年全球十大半导体厂商:英特尔重回第一,苹果逆势大涨