Copy file (can display progress bar) [original]

xiaoxiao2021-03-06  60

A few days ago, I saw a netizen in 9CBS to use asynchronous to write a similar to this stuff, now I also write my ideas, everyone study each other. I launched a new thread in the main thread to copy, then the main thread is subscribed to the new thread, and define the relevant processing method to process the event. The interface is as follows: Some of the code implemented below. 1, the main class of copies of the file: Class DOWORKS {// set a entrustment public delegate void CopyFileHandler (long lngposition, long lngcount); // Define an event (very important), this event will be captured by the main thread, And change the content of the main thread, such as: progress bar. Public Event CopyFileHandler CopyFileEvent; // Defines two string variables, sfile indicates that the source file, TFile represents the target file, of course, this can use the properties, this for simplicity, use a common variable directly. Public system.string sfile; public system.string tfile;

// This is the method used by the working thread. Public void copyfile () {// Defines a byte array to cache the byte stream read from the source file. Byte [] fb = new byte [2048]; // Defines the current read byte to the main thread update interface. Long lngposition = 0; // Source File Filestream SFS = New FileStream (Sfile, System.IO.Filemode.Open, System.IO.FileMode.Open, System.IO.FileAccess.Read; // Binary Reader BinaryReader Br = New BinaryReader (SFS) Br.Basestream.seek (0, system.io.seekorigin.begin); if (file.exists (tfile)) file.delete (tfile); // Target file stream FileStream TFS = New FileStream (tfile, system.io .Filemode.createNew, system.io.fileAccess.write;

// Binary file writer BinaryWriter BW = New BinaryWriter (TFS); // Source file size long positionLENGTH = sfs.length; int K = 10000; // When the number of bytes read is less than 2048, it is read The end of the file stream. Stop reading while (k> = 2048) {k = br.read (fb, 0, fb.length);

BW.WRITE (FB);

转载请注明原文地址:https://www.9cbs.com/read-83823.html

New Post(0)