19 using System.Collections.Generic;
23 using System.Security.Cryptography;
29 #region Public methods 38 using (FileStream fs = SafeFileStream(file))
40 using (BufferedStream bs =
new BufferedStream(fs))
42 using (SHA256Managed sha =
new SHA256Managed())
44 string hash = Checksum2Hash(sha.ComputeHash(bs));
45 Logger.Info(
"Sha256Hash: {0}", file);
46 Logger.Info(
"Sha256Hash: {0}", hash);
59 byte[] bytes = Encoding.UTF8.GetBytes(exception.ToString());
60 using (SHA256Managed sha =
new SHA256Managed())
62 string hash = Checksum2Hash(sha.ComputeHash(bytes));
63 Logger.Info(
"Sha256Hash: {0}", exception.GetType().ToString());
64 Logger.Info(
"Sha256Hash: {0}", hash);
76 using (FileStream fs = SafeFileStream(file))
78 using (BufferedStream bs =
new BufferedStream(fs))
80 using (SHA1Managed sha =
new SHA1Managed())
82 string hash = Checksum2Hash(sha.ComputeHash(bs));
83 Logger.Info(
"Sha1Hash: {0}", file);
84 Logger.Info(
"Sha1Hash: {0}", hash);
91 private static string Checksum2Hash(byte[] bytes)
93 StringBuilder formatted =
new StringBuilder(2 * bytes.Length);
94 foreach (byte b
in bytes)
96 formatted.AppendFormat(
"{0:x2}", b);
98 return formatted.ToString();
103 #region Private methods 110 private static FileStream SafeFileStream(
string file)
113 FileStream fs = null;
115 Logger.Info(
"SaveFileStream: Attempting to open \"{0}\"", file);
116 while (tries <= 3 && fs == null)
120 fs =
new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
124 Logger.Warn(
"SafeFileStream: Failed to open stream on attempt #{0}", tries);
127 System.Threading.Thread.Sleep(333);
133 Logger.Fatal(
"SafeFileStream: Unable to open stream in #{0} attempts!");
134 throw new IOException(
"Unable to access file", ex);
143 private static NLog.Logger Logger {
get {
return _logger.Value; } }
145 private static readonly Lazy<
NLog.Logger> _logger =
new Lazy<
NLog.Logger>(() =>
NLog.LogManager.GetCurrentClassLogger());
static string Sha1Hash(string file)
Computes the Sha1 hash of a given file.
static string Sha256Hash(Exception exception)
Computes the Sha256 hash of an exception.
static string Sha256Hash(string file)
Computes the Sha256 hash of a given file.