Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.IO;
- using System.Security.Cryptography;
- ...
- public byte[] HashedFileWrite(string filename, Stream input)
- {
- var hash_algorithm = MD5.Create();
- using(var file = File.OpenWrite(filename))
- {
- byte[] buffer = new byte[4096];
- int read = 0;
- while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
- {
- hash_algorithm.TransformBlock(buffer, 0, read, null, 0);
- file.Write(buffer, 0, read);
- }
- hash_algorithm.TransformFinalBlock(buffer, 0, read);
- }
- return hash_algorithm.Hash;
- }
- private static byte[] CopyAndHash(string source, string target, Action<double> progress, Func<bool> isCanceled)
- {
- using(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));
- return sha512.Hash;
- }
- }
- Stream s = File.Open("infile.dat");
- Stream out = File.Create("outfile.dat");
- HashWrapStream hasher = new HashWrapStream(out);
- byte[] buffer=new byte[1024];
- int read = 0;
- while ((read=s.Read(buffer)!=0)
- {
- hasher.Write(buffer);
- }
- long hash=hasher.GetComputedHash(); // get actual hash
- hasher.Dispose();
- s.Dispose();
- //var ticks = **some_array_you_want_to_write_as_csv**
- using (var memoryStream = new System.IO.MemoryStream())
- {
- using (var textWriter = new System.IO.StreamWriter(memoryStream))
- {
- using (var csv = new CsvHelper.CsvWriter(textWriter))
- {
- csv.Configuration.DetectColumnCountChanges = true; //error checking
- csv.Configuration.RegisterClassMap<TickDataClassMap>();
- csv.WriteRecords(ticks);
- textWriter.Flush();
- //write to disk
- using (var fileStream = new System.IO.FileStream(targetFileName, System.IO.FileMode.Create))
- {
- memoryStream.Position = 0;
- memoryStream.CopyTo(fileStream);
- }
- //write sha256 hash, ensuring that the file was properly written
- using (var sha256 = System.Security.Cryptography.SHA256.Create())
- {
- memoryStream.Position = 0;
- var hash = sha256.ComputeHash(memoryStream);
- using (var reader = System.IO.File.OpenRead(targetFileName))
- {
- System.IO.File.WriteAllText(targetFileName + ".sha256", hash.ConvertByteArrayToHexString());
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment