static void Main (string [] args)
{
Console.WriteLine (SHA256File (@ "C: \ BaiduYunDownload \ 66666.jpg"));
}
/// Calculate the SHA256 value of the file
/// </ summary>
/// <param name = "fileName"> File name and path to calculate SHA256 value </ param>
/// <returns> SHA256 value hex string </ returns>
public static string SHA256File (string fileName)
{
return HashFile (fileName, "sha256");
}
/// <summary>
/// Calculate the hash value of the file
/// </ summary>
/// <param name = "fileName"> File name and path to calculate hash value </ param>
/// <param name = "algName"> Algorithm: sha1, md5 </ param>
/// <returns> hash hex string </ returns>
public static string HashFile (string fileName, string algName)
{
if (! System.IO.File.Exists (fileName))
return string.Empty;
FileStream fs = new FileStream (fileName, FileMode.Open, FileAccess.Read);
byte [] hashBytes = HashData (fs, algName);
fs.Close ();
return ByteArrayToHexString (hashBytes);
}
/// <summary>
/// convert byte array to hexadecimal string
/// </ summary>
public static string ByteArrayToHexString (byte [] buf)
{
string returnStr = "";
if (buf! = null)
{
for (int i = 0; i <buf.Length; i ++)
{
returnStr + = buf [i] .ToString ("X2");
}
}
return returnStr;
}
/// <summary>
/// Calculate the hash value
/// </ summary>
/// <param name = "stream"> Stream to be hashed </ param>
/// <param name = "algName"> Algorithm: sha1, md5 </ param>
/// <returns> Hash byte array </ returns>
public static byte [] HashData (Stream stream, string algName)
{
HashAlgorithm algorithm;
if (algName == null)
{
throw new ArgumentNullException ("algName cannot be null");
}
if (string.Compare (algName, "sha256", true) == 0)
{
algorithm = SHA256.Create ();
}
else
{
if (string.Compare (algName, "md5", true)! = 0)
{
throw new Exception ("algName can only use sha256 or md5");
}
algorithm = MD5.Create ();
}
return algorithm.ComputeHash (stream);
}
C # computes the SHA256 value of a file