当前位置:网站首页>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 .
边栏推荐
- In 2019, the world's top ten semiconductor manufacturers: Intel returned to the first place, and apple rose sharply against the trend
- Record the errors about formatc in R language
- Reduce error demonstration
- 五子棋人机对战实现
- 虚拟存储器与Cache的比较
- Put cloudflare on the website (take Tencent cloud as an example)
- [NPUCTF2020]EzRSA
- NDK series (6): let's talk about the way and time to register JNI functions
- Why do I need to wait for 2msl?
- 76000 people shut down! Toshiba announced the closure of all factories in Japan
猜你喜欢

给网站套上Cloudflare(以腾讯云为例)

2022 summer vacation daily question (5)

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

Record the errors about formatc in R language

Unity 实现简单画板画画功能(笔记)

UE4官方AEC蓝图案例课程学习笔记

Character stream learning 14.3

Master data management theory and Practice

My annual salary is 1million, and I don't have clothes more than 100 yuan all over my body: saving money is the top self-discipline

NDK 系列(6):说一下注册 JNI 函数的方式和时机
随机推荐
File&递归14.1
为什么需要等待计时2MSL?
BUUCTF-[BJDCTF2020]RSA1
MapReduce (III)
加速IGBT国产化!比亚迪半导体将独立上市,市值或达300亿元!
Latex常用总结(2):输入矩阵(输入矩阵、对角阵、方程组等)
JS提升:JS中的数组扁平化问题
面试官问线程安全的List,看完再也不怕了!
Apple releases new iPhone se: equipped with A13 bionic processor, priced from 3299 yuan
Application of user portrait in precise push of wechat official account of scientific journals
[GWCTF 2019]BabyRSA1
BUUCTF-bbbbbbrsa
Flutter pull_ to_ refresh-1.6.0/lib/src/internals/slivers. dart:164:13: Error: Method not found: ‘descr
Error:svn: E155010: ‘/Users/.../Desktop/wrokspace/xxx‘ is scheduled for addition, but is missing
【12月海口】2022年第六届船舶,海洋与海事工程国际会议(NAOME 2022)
Bank Marketing预测一个客户购买理财产品的成功率
Reinforcement learning - pytorch realizes advantage actor critical (A2C)
The first activity of togaf10 standard reading club was successfully held, and the wonderful moments were reviewed!
主数据管理理论与实践
Unity 实现简单画板画画功能(笔记)