force-net / Crc32.NET

Fast version of Crc32 algorithm for .NET
MIT License
199 stars 52 forks source link

How exactly do I use this to calculate CRC value for a file? #7

Open cryodream opened 6 years ago

cryodream commented 6 years ago

Hi, Like the title says, how do I use this library to calculate hashes for files?

Thanks for any help.

force-net commented 6 years ago

Example code:

var crc = 0u;
using (var f = File.OpenRead("somefile"))
{
    var buffer = new byte[65536];
    while (true)
    {
        var count = f.Read(buffer, 0, buffer.Length);
        if (count == 0)
            break;
        crc = Crc32Algorithm.Append(crc, buffer, 0, count);
    }
}

Console.WriteLine(crc);
kgamecarter commented 5 years ago
using (var stream = new FileStream(path, FileMode.Open))
using (var crc = new Crc32Algorithm())
{
    var crc32bytes = crc.Compute(stream);
    var crc32 = BitConverter.ToUInt32(crc32bytes, 0);
}
Agagamand commented 5 years ago

This better:

private string GetCRC32C(string filename, IProgress<double> progress = null)
{
    uint hash = 0;
    byte[] buffer = new byte[1048576]; // 1MB buffer

    using (var entryStream = File.OpenRead(filename))
    {
        int currentBlockSize = 0;

        while ((currentBlockSize = entryStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            hash = Crc32CAlgorithm.Append(hash, buffer, 0, currentBlockSize);
            progress?.Report((double)currentBlockSize / entryStream.Length * 100);
        }
    }
    return hash.ToString("X8");
}

Maybe you should add this example to the Wiki? https://github.com/force-net/Crc32.NET/wiki

PeterCodar commented 4 years ago

This better:

Could you please let us know why this [is] better?

force-net commented 4 years ago

@PeterCodar I do not know... Differences:

EnduringBeta commented 3 years ago

Adding one or more working examples to the readme would dramatically improve a person's experience using the package if new to them, like me. Thanks to those who asked and answered this question over here.