HashAlgorithm.ComputeHash Method (Stream)
.NET Framework 4.5
Computes the hash value for the specified Stream object.
Namespace: System.Security.Cryptography
Assembly: mscorlib (in mscorlib.dll)
Parameters
- inputStream
- Type: System.IO.Stream
The input to compute the hash code for.
| Exception | Condition |
|---|---|
| ObjectDisposedException | The object has already been disposed. |
The following example calculates the RIPEMD160 hash for all files in a directory.
using System; using System.IO; using System.Security.Cryptography; using System.Windows.Forms; public class HashDirectory { [STAThreadAttribute] public static void Main(String[] args) { string directory = ""; if (args.Length < 1) { FolderBrowserDialog fbd = new FolderBrowserDialog(); DialogResult dr = fbd.ShowDialog(); if (dr == DialogResult.OK) directory = fbd.SelectedPath; else { Console.WriteLine("No directory selected."); return; } } else directory = args[0]; try { // Create a DirectoryInfo object representing the specified directory. DirectoryInfo dir = new DirectoryInfo(directory); // Get the FileInfo objects for every file in the directory. FileInfo[] files = dir.GetFiles(); // Initialize a RIPE160 hash object. RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create(); byte[] hashValue; // Compute and print the hash values for each file in directory. foreach (FileInfo fInfo in files) { // Create a fileStream for the file. FileStream fileStream = fInfo.Open(FileMode.Open); // Be sure it's positioned to the beginning of the stream. fileStream.Position = 0; // Compute the hash of the fileStream. hashValue = myRIPEMD160.ComputeHash(fileStream); // Write the name of the file to the Console. Console.Write(fInfo.Name + ": "); // Write the hash value to the Console. PrintByteArray(hashValue); // Close the file. fileStream.Close(); } return; } catch (DirectoryNotFoundException) { Console.WriteLine("Error: The directory specified could not be found."); } catch (IOException) { Console.WriteLine("Error: A file in the directory could not be accessed."); } } // Print the byte array in a readable format. public static void PrintByteArray(byte[] array) { int i; for (i = 0; i < array.Length; i++) { Console.Write(String.Format("{0:X2}", array[i])); if ((i % 4) == 3) Console.Write(" "); } Console.WriteLine(); } }
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.