using System.Security.Cryptography; using System.Text; public string ComputeSHA1(string input) { // Convert input string to byte array byte[] inputBytes = Encoding.UTF8.GetBytes(input); // Create SHA1Managed instance SHA1Managed hash = new SHA1Managed(); // Compute hash of input bytes byte[] outputBytes = hash.ComputeHash(inputBytes); // Convert hash output to string string output = BitConverter.ToString(outputBytes).Replace("-", ""); return output; }
using System.Security.Cryptography; using System.IO; public string ComputeFileSHA1(string path) { // Create SHA1Managed instance SHA1Managed hash = new SHA1Managed(); // Open file and compute hash of contents using (FileStream stream = File.OpenRead(path)) { byte[] outputBytes = hash.ComputeHash(stream); string output = BitConverter.ToString(outputBytes).Replace("-", ""); return output; } }In this example, we create an instance of SHA1Managed and use a FileStream to compute the hash of a file's contents. We open the file using File.OpenRead and pass the resulting stream to ComputeHash. Finally, we return the hash output as a string.