Introduction
This class makes an async file copy. It uses a Buffer and makes cyclic reads.
Background
The code is useful in case of signature arrays to be checked at run-time.
Using the code
To start the copy call the StartCopy
function.
class FileCopy
{
#region KeepThem10MultiplyToAvoidDoubleCopy
const int sizeBufferCopy= 10485760;
const int sizeCyclicRead = 1048576;
#endregion
private UInt64 indRd, indWr, nrReadings, nrWritings, nrReadsWrites, nrBytesWereRead;
private bool finishedRd= false, startCopy = true;
byte[] BufferCopy;
private string destinationFile, sourceFile;
public FileCopy(string d, string s)
{
destinationFile = d; sourceFile = s;
}
public bool StartCopy()
{
bool retValue = false;
if ((destinationFile != string.Empty) && (sourceFile != string.Empty))
{
Thread newThreadCopy = new Thread(ReadWorker);
Thread newThreadWrite = new Thread(WriteWorker);
newThreadCopy.Start();
newThreadWrite.Start();
retValue = true;
}
return retValue;
}
private void WriteWorker()
{
UInt16 SleepTime = 10;
UInt64 nrBytesWriten = sizeCyclicRead;
do
{
Thread.Sleep(10);
} while (indRd == 0);
using (BinaryWriter writer = new BinaryWriter(File.Open(destinationFile, FileMode.Create)))
{
do
{
if ((finishedRd == false) && (nrWritings >= (nrReadings - 1)))
{
Thread.Sleep(SleepTime);
SleepTime += 10;
}
else
{
if (indWr >= sizeBufferCopy)
{
indWr = 0;
}
if (nrWritings == nrReadsWrites - 1)
{
nrBytesWriten = nrBytesWereRead;
}
writer.Write(BufferCopy, (Int32)indWr, (Int32) nrBytesWriten);
indWr += sizeCyclicRead;
++nrWritings;
}
} while (nrWritings < nrReadsWrites);
}
}
private void ReadWorker()
{
FileStream f = File.Open(sourceFile, FileMode.Open);
UInt64 Length = (UInt64)f.Length, pos = 0;
BufferCopy = new byte[sizeBufferCopy];
nrReadsWrites = Length / sizeCyclicRead + 1;
UInt16 SleepTime = 10;
using (BinaryReader binR = new BinaryReader(f))
{
while(pos < Length)
{
startCopy = false;
if ((startCopy) || (indRd >= (indWr + sizeBufferCopy - 1)))
{
Thread.Sleep(SleepTime);
SleepTime += 10;
}
else
{
byte[] BufferRd = binR.ReadBytes(sizeCyclicRead);
nrBytesWereRead = (UInt64) BufferRd.Length;
if (indRd >= sizeBufferCopy)
{
indRd = 0;
}
Array.Copy(BufferRd, 0, BufferCopy, (Int64)indRd, (Int64)nrBytesWereRead);
indRd += nrBytesWereRead;
pos += nrBytesWereRead;
++nrReadings;
}
}
}
finishedRd= true;
}
}