Skip to content

Instantly share code, notes, and snippets.

@dhcgn
Last active June 14, 2017 14:51
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 dhcgn/da1637277d9456db9523a96a0a34da78 to your computer and use it in GitHub Desktop.
Save dhcgn/da1637277d9456db9523a96a0a34da78 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FileCopyAndHash
{
class Program
{
static void Main(string[] args)
{
var input = Path.GetTempFileName();
var data = Guid.NewGuid().ToByteArray();
File.WriteAllBytes(input, data);
var output = Path.GetTempFileName();
var hash = CopyAndHash(input, output, d => Console.WriteLine($"Progress: {d}%"), () => false);
Console.WriteLine("Content: " + Convert.ToBase64String(data));
if (data.SequenceEqual(File.ReadAllBytes(output)))
Console.Out.WriteLine("File is equal!");
else
Console.Out.WriteLine("File is NOT equal!");
Console.WriteLine("Hash: " + Convert.ToBase64String(hash));
if (SHA512.Create().ComputeHash(File.ReadAllBytes(output)).SequenceEqual(hash))
Console.Out.WriteLine("hash is equal!");
else
Console.Out.WriteLine("hash is NOT equal!");
Console.ReadKey();
}
private static byte[] CopyAndHash(string source, string target, Action<double> progress, Func<bool> isCanceled)
{
var sha512 = SHA512.Create();
using (var targetStream = File.OpenWrite(target))
using (var cryptoStream = new CryptoStream(targetStream, sha512, CryptoStreamMode.Write))
using (var sourceStream = File.OpenRead(source))
{
byte[] buffer = new byte[81920];
int read;
while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0 && !isCanceled())
{
cryptoStream.Write(buffer, 0, read);
progress?.Invoke((double) sourceStream.Length / sourceStream.Position * 100);
}
}
File.SetAttributes(target, File.GetAttributes(source));
var hash = sha512.Hash;
sha512.Dispose();
return hash;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment