-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
99 lines (80 loc) · 2.59 KB
/
Copy pathProgram.cs
File metadata and controls
99 lines (80 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace FIleHasher
{
class Program
{
private static BackgroundWorker bgWorker;
static void Main()
{
// set the background worker events
bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgressChanged);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
bgWorker.WorkerReportsProgress = true;
// set the console content
Console.Title = "File Hasher";
// create a variable to store the path of the file to compute the hash of
string filePath = string.Empty;
// prompt the user to enter a file path
Console.WriteLine("Please enter the path for the file you'd like to hash:");
// get the user input
filePath = Console.ReadLine();
if (filePath == "this" || filePath == "." || filePath == "")
filePath = Application.ExecutablePath;
// run the background worker to compute the file's hash
bgWorker.RunWorkerAsync(filePath);
// let the user know the hash is being computed
Console.WriteLine("\nComputing hash...\n");
Console.ReadLine();
Console.Clear();
}
private static void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
string filePath = e.Argument.ToString();
byte[] buffer;
int bytesRead;
long size;
long totalBytesRead = 0;
using (Stream file = File.OpenRead(filePath))
{
size = file.Length;
using (HashAlgorithm hasher = MD5.Create())
{
do
{
buffer = new byte[4096];
bytesRead = file.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
hasher.TransformBlock(buffer, 0, bytesRead, null, 0);
bgWorker.ReportProgress((int)((double)totalBytesRead / size * 100));
}
while (bytesRead != 0);
hasher.TransformFinalBlock(buffer, 0, 0);
e.Result = MakeHashString(hasher.Hash);
}
}
}
private static void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.Title = string.Format("File Hasher - {0}%", e.ProgressPercentage);
}
private static void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.Write(e.Result.ToString());
}
private static string MakeHashString(byte[] hashBytes)
{
StringBuilder hash = new StringBuilder(32);
foreach (byte b in hashBytes)
hash.Append(b.ToString("X2").ToLower());
return hash.ToString();
}
}
}