Introduction
CRC (Cyclic Redundancy Check) is commonly used as a way to confirm that a file had not corrupted during download. While convenient, it takes some time to read the data off of the disk after downloading for the check. It would be convenient if applications checked the CRC on-the-fly during download, so as not to waste idle CPU time and disk read time.
Downloading is done at a relatively leisurely pace (typically anywhere between 5-300kb/s) and over a long period of time, so it makes for a great opportunity to process data without impeding performance. Although ugly and impractical for most applications (it'd be safe to assume that most users think they've "broken the intarweb" when they see a hex number), displaying the CRC to the user immediately as a download finishes can often be a well-appreciated bonus.
This class passively calculates CRCs as data passes through it, ready to be used at any time.
Using the code
To calculate the CRC of a file as it is read to the end, create a new CrcStream
passing the FileStream
as an argument, and use the ReadCrc
property to retrieve the CRC. Be sure to use the new CrcStream
instead of the file stream to read from the file; otherwise the checksum will not be calculated.
FileStream file = new FileStream(filename, FileMode.Open);
CrcStream stream = new CrcStream(file);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
Console.WriteLine("CRC: " + stream.ReadCrc.ToString("X8"));
There are four public members in addition to the abstract Stream
overrides:
ReadCrc
- gets the checksum of the data that was read through the stream.
WriteCrc
- gets the checksum of the data that was written to the stream.
ResetChecksum
- resets the CRC values.
Stream
- gets the encapsulated stream.