RingDotNetfor Ring

Copying a big file with progress

File.Copy copies a file in one call, but a program that shows a progress bar or can be canceled reads and writes the file in pieces. This lesson copies 3,000,000 bytes through a 64 KB byte buffer, reports the progress, cancels half way, checks the copy with a checksum and compares buffer sizes.

What you will learn#

The tutorial Binary files introduced the byte buffer. Here the buffer does the work of a copy.

The program#

samples/UsingDotNet/tutorials/ch05_copy_progress.ring
# copying a big file with progress - reading and writing in pieces with a byte buffer, a percentage, cancelling, and checking the copy
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.Security.Cryptography"
}

func main

	oPath = new Path()
	oFile = new File()
	cFolder = oPath.Combine([ oPath.GetTempPath(), "ringdotnet-copy-" + oPath.GetRandomFileName() ])
	new Directory().CreateDirectory(cFolder)
	cSource = cFolder + "/source.bin"
	cTarget = cFolder + "/target.bin"

	# A source file of 3,000,000 bytes: a pattern of all 256 byte values, repeated (the program makes it, so that the output is always the same)
	cBlock = ""
	for i = 0 to 255
		cBlock += char(i)
	next
	cData = ""
	for i = 1 to 11719
		cData += cBlock
	next
	cData = left(cData,3000000)
	oFile.WriteAllBytes(cSource,cData)
	? "1. the source file has " + new FileInfo(cSource).Length + " bytes"

	# 2. A copy in PIECES. File.Copy does it in one call, but a program that shows a progress bar, or that can be canceled, reads and writes
	#    a piece at a time. The piece is a BYTE BUFFER (dnBuffer): Read fills it, and Write sends the same buffer on, so the bytes are
	#    never turned into a Ring text. The buffer has 64 KB: a small buffer means many calls, a huge one wastes memory.
	? nl + "2. copy with a progress report at each quarter:"
	nCopied = copyFile(cSource,cTarget,65536,0)
	? "   copied " + nCopied + " bytes"

	# 3. Check the copy: the same size and the same SHA-256 checksum (the tutorial about checking that files did not change)
	? nl + "3. the copy is complete: sizes " + yesNo(new FileInfo(cSource).Length = new FileInfo(cTarget).Length) + ", checksums " + yesNo(checksum(cSource) = checksum(cTarget))

	# 4. Cancel. The program stops after 1,000,000 bytes, as if the user pressed Cancel. A half copy is worse than none, so the target is deleted.
	oFile.Delete(cTarget)
	? nl + "4. cancel after 1,000,000 bytes:"
	nCopied = copyFile(cSource,cTarget,65536,1000000)
	? "   stopped at " + nCopied + " bytes; the half copy is deleted: " + yesNo(not oFile.Exists(cTarget))

	# 5. The size of the buffer. The last piece is smaller than the buffer, and Read says how many bytes it gave. A buffer of 1 byte
	#    would work and be very slow: count the calls for three sizes.
	? nl + "5. the number of Read calls for the 3,000,000 bytes:"
	for nSize in [ 4096, 65536, 1048576 ]
		? "   buffer of " + padLeft("" + nSize,8) + " bytes: " + countCalls(cSource,nSize) + " calls"
	next

	new Directory().Delete([ :path = cFolder, :recursive = True ])

# Copy a file in pieces. Progress is printed for the first piece after each quarter (the pieces are 64 KB, so it is a little over 25 percent). nStopAfter > 0 cancels when that many bytes were copied; the
# target is then deleted. The answer is the number of bytes copied.
func copyFile cSource,cTarget,nBufferSize,nStopAfter

	oIn = (new FileStream).@New([ :path = cSource, :mode = "Open", :access = "Read" ])
	oOut = (new FileStream).@New([ :path = cTarget, :mode = "Create", :access = "Write" ])
	nTotal = oIn.Length
	oBuffer = dnBuffer(nBufferSize)
	nCopied = 0
	nQuarter = 0
	lCanceled = False
	while True
		nRead = oIn.Read(oBuffer,0,nBufferSize)
		if nRead = 0
			exit                                          # Read gives 0 at the end of the file
		ok
		oOut.Write(oBuffer,0,nRead)                       # only the nRead bytes that were read
		nCopied += nRead
		nPercent = floor(100 * nCopied / nTotal)
		if floor(nPercent / 25) > nQuarter
			nQuarter = floor(nPercent / 25)
			? "   " + nPercent + " percent (" + nCopied + " of " + nTotal + " bytes)"
		ok
		if nStopAfter > 0 and nCopied >= nStopAfter
			lCanceled = True
			exit
		ok
	end
	oOut.Dispose()
	oIn.Dispose()
	if lCanceled
		new File().Delete(cTarget)
	ok
	return nCopied

# how many calls of Read a buffer of this size needs for the whole file
func countCalls cFile,nBufferSize

	oIn = (new FileStream).@New([ :path = cFile, :mode = "Open", :access = "Read" ])
	oBuffer = dnBuffer(nBufferSize)
	nCalls = 0
	while oIn.Read(oBuffer,0,nBufferSize) > 0
		nCalls++
	end
	oIn.Dispose()
	return nCalls

func checksum cFile

	return new Convert().ToHexString(new SHA256().HashData(new File().ReadAllBytes(cFile)))

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"

func padLeft cText,nWidth

	return copy(" ",nWidth - len(cText)) + cText
Output
1. the source file has 3000000 bytes

2. copy with a progress report at each quarter:
   26 percent (786432 of 3000000 bytes)
   50 percent (1507328 of 3000000 bytes)
   76 percent (2293760 of 3000000 bytes)
   100 percent (3000000 of 3000000 bytes)
   copied 3000000 bytes

3. the copy is complete: sizes yes, checksums yes

4. cancel after 1,000,000 bytes:
   26 percent (786432 of 3000000 bytes)
   stopped at 1048576 bytes; the half copy is deleted: yes

5. the number of Read calls for the 3,000,000 bytes:
   buffer of     4096 bytes: 733 calls
   buffer of    65536 bytes: 46 calls
   buffer of  1048576 bytes: 3 calls
Note

This program uses a few generic functions (dnNew, dnBuffer) where a class cannot be used. The lesson The generic functions explains them.

How it works#

The loop#

copyFile opens the source for reading and the target for writing (Create makes a new file), and makes one buffer of 64 KB. The loop is always the same: Read fills the buffer and answers how many bytes it wrote, Write sends those bytes on, and the loop ends when Read answers 0, the end of the file. The same buffer is used again and again, so the program needs 64 KB of memory for a file of any size.

Read gives a number#

Read(buffer, 0, size) may write fewer bytes than the buffer holds: the last piece of a file is almost always smaller (the file here has 3,000,000 bytes, and the last piece has 3,000,000 − 45 × 65,536 bytes). The program writes nRead bytes, not the size of the buffer; writing the whole buffer would add bytes to the end of the copy.

No Ring text in the middle#

Write(oBuffer, 0, nRead) takes the buffer itself: the bytes go from the file to the buffer and from the buffer to the other file inside .NET, and are never turned into a Ring text. That is faster, and it is the reason to use a buffer even though a Ring text can hold the bytes. A program that must look at the bytes (to count something, to search) reads them with dnBufferBytes(oBuffer, nRead).

Progress#

After each piece the program knows how many bytes were copied and the total (Length of the source), so the percentage is 100 * copied / total. The program prints a line the first time that the percentage passes 25, 50, 75 and 100. A window program sets a progress bar at this place, and handles the events of the window in the loop so that it does not freeze (the tutorial Timers and progress does the same with a timer).

Cancel#

A canceled copy leaves a half file, which is worse than no file: somebody may use it. The function stops when the limit is reached, closes both streams (Dispose), and deletes the target. The same pattern is used for an error in the middle: close, delete, report.

Check the copy#

A copy is complete when the size is the same and the checksum is the same (the tutorial A project: check that files did not change). The size is a quick check, and the checksum proves that every byte is the same.

The size of the buffer#

With a buffer of 4 KB the 3,000,000 bytes need 733 calls of Read, with 64 KB 46 calls and with 1 MB only 3. Every call crosses the bridge, so a very small buffer is slow, and a very big one wastes memory and gives the user fewer progress reports. Sizes between 16 KB and 1 MB are usual.

What you learned#

Exercises#

  1. Show the speed in megabytes per second (a Stopwatch, the tutorial Speed: measure first).
  2. Copy two files at once by taking one piece from each in turn.
  3. Make moveFile that copies and deletes the source only after the checksums are equal.
  4. Resume an interrupted copy: open the target with Append, seek the source to the size of the target, and go on.

Next#

What kind of file is it?

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.