How to calculate hash using streams while saving file to disk?
I don't want to: Save the file first and then load it from disk just to calculate the hash, at any point having to load the entire file into memory, use non async version of methods for which there is async counterpart or use API which is marked as obsolete in .NET 6 or higher.
This is what I have so far always getting "err"
public async Task HashOnTheFly()
{
var path = "/tmp/a.txt";
await SaveAsync(File.OpenRead(path), "/tmp/b.txt", default);
async Task SaveAsync(Stream stream, string path, CancellationToken ct)
{
var sha512 = SHA512.Create();
var fileName = Path.GetFileName(path);
var destinationPath = Path.Combine("/tmp", fileName);
await using var fileStream = File.Create(destinationPath);
await using var cryptoStream = new CryptoStream(fileStream, sha512, CryptoStreamMode.Read);
await stream.CopyToAsync(fileStream, ct);
if (sha512?.Hash is { } computedHash)
Console.WriteLine(computedHash);
else
Console.WriteLine("err");
}
}