Code
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Threading;
Using System. IO;
Namespace ExToDB. FileTransfer
{
Public class FileComsumer
{
Private string fileName;
Private Stream streamOuput = null;
Private int bufferSize = 1024;
Private Thread fileThread = null;
Private volatile bool isStop;
Public event ReturnEndEvent OnReadEnd;
Public FileComsumer (string fileName)
{
IsStop = false;
This. fileName = fileName;
}
/// <Summary>
/// Obtain the read Stream
/// </Summary>
Public Stream StreamOuput
{
Get {return streamOuput ;}
}
Public void Start ()
{
FileThread = new Thread (new ThreadStart (TheadReadFile ));
FileThread. Start ();
}
Public void Stop ()
{
IsStop = true;
If (fileThread! = Null & fileThread. ThreadState = System. Threading. ThreadState. Running)
FileThread. Abort ();
FileThread = null;
}
Private byte [] buffer = null;
/// <Summary>
/// Obtain the read data
/// </Summary>
Public byte [] Buffer
{
Get {return buffer ;}
}
Private void TheadReadFile ()
{
StreamOuput = new FileStream (fileName, FileMode. Open, FileAccess. Read, FileShare. Read, bufferSize, true );
Int numBytesToRead = (int) streamOuput. Length;
Int numBytesRead = 0;
Buffer = new byte [streamOuput. Length];
While (numBytesToRead> 0 &&! IsStop)
{
// Read may return anything from 0 to numBytesToRead.
Int n = streamOuput. Read (buffer, numBytesRead, numBytesToRead );
// The end of the file is reached.
If (n = 0)
{
OnOnReadEnd ();
Break;
}
NumBytesRead + = n;
NumBytesToRead-= n;
// File Reading is complete, triggering the event
If (numBytesToRead = 0)
OnOnReadEnd ();
}
StreamOuput. Close ();
}
Private void OnOnReadEnd ()
{
If (this. OnReadEnd! = Null)
OnReadEnd (this, new ReturnEndReadEventargs (true ));
}
}
}