Skip to content

Instantly share code, notes, and snippets.

@mjs3339
Last active January 27, 2019 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjs3339/5b6d86b8a317a7c84dcd5fdbe7672900 to your computer and use it in GitHub Desktop.
Save mjs3339/5b6d86b8a317a7c84dcd5fdbe7672900 to your computer and use it in GitHub Desktop.
C# 128 Bit ASynchronous File Hashing Class using the MurMur3 Hashing Algorithm
public class FileHash128 : Murmur3
{
private const int BufferSize = 1024 * 80;
private readonly byte[] buffer = new byte[1073741823];
public byte[] GetFileHashSync(string path)
{
var fLen = 0;
using(var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, false))
{
var offset = 0;
var length = fileStream.Length;
if(length > 1073741823)
throw new ArgumentOutOfRangeException("File Size exceeds 1gb.");
var count = (int) length;
fLen = count;
int nRead;
while(count > 0)
{
nRead = fileStream.Read(buffer, offset, count);
if(nRead == 0)
break;
offset += nRead;
count -= nRead;
}
}
return ComputeHash(buffer, 0, fLen);
}
public async Task<byte[]> GetFileHashAsync(string path)
{
var fLen = 0;
using(var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, true))
{
var offset = 0;
var count = (int) fileStream.Length;
if(count > 1073741823)
throw new ArgumentOutOfRangeException("File Size exceeds 1gb.");
fLen = count;
while(count > 0)
{
var nRead = await fileStream.ReadAsync(buffer, offset, count).ConfigureAwait(false);
if(nRead == 0)
break;
offset += nRead;
count -= nRead;
}
}
return ComputeHash(buffer, 0, fLen);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment