R. McGraw said:
Is there a CRC function in .NET where I can to a check for a valid
file transfer, or does someone have a code snippet I can have?
My encodedstreams library has a CRC class:
http://www.grimes.demon.co.uk/dotnet/encodedStreams.htm
Here's the code I use:
// Calculate CRC from stream data
public class CRC32
{
private uint[] crc32Table;
private const int BUFFER_SIZE = 1024;
public CRC32()
{
Initialize();
}
public CRC32(uint crc, int count)
{
Initialize();
if (count == 0)
{
this.crc = 0xFFFFFFFF;
this.count = count;
}
else
{
// The CRC that has been returned previously needs to have its
// bits flipped so that it can be used for the partial CRC
this.crc = ~crc;
this.count = count;
}
}
// Initialize the CRC table
private void Initialize()
{
unchecked
{
// This is the official polynomial used by CRC32 in PKZip.
// Often the polynomial is shown reversed as 0x04C11DB7.
uint dwPolynomial = 0xEDB88320;
uint i, j;
crc32Table = new uint[256];
uint dwCrc;
for (i = 0; i < 256; i++)
{
dwCrc = i;
for (j = 8; j > 0; j--)
{
if ((dwCrc & 1)==1)
{
dwCrc = (dwCrc >> 1) ^ dwPolynomial;
}
else
{
dwCrc >>= 1;
}
}
crc32Table
= dwCrc;
}
}
}
uint crc = 0xFFFFFFFF;
int count = 0;
// Add a byte to the CRC
public void CheckByte(byte b)
{
unchecked
{
crc = ((crc) >> 8)
^ crc32Table[(b) ^ ((crc) & 0x000000FF)];
}
count++;
}
// Get the CRC for an entire stream
public uint GetCrc32(Stream stream)
{
unchecked
{
uint crc32Result;
crc32Result = 0xFFFFFFFF;
byte[] buffer = new byte[BUFFER_SIZE];
int readSize = BUFFER_SIZE;
int count = stream.Read(buffer, 0, readSize);
while (count > 0)
{
for (int i = 0; i < count; i++)
{
crc32Result = ((crc32Result) >> 8) ^
crc32Table[(buffer) ^ ((crc32Result) & 0x000000FF)];
}
count = stream.Read(buffer, 0, readSize);
}
return ~crc32Result;
}
}
// Return the CRC
public uint CRC
{
get{return ~crc;}
}
}
Richard