HashAlgorithm.ComputeHash Method (Stream)


Computes the hash value for the specified Stream object.

Namespace:   System.Security.Cryptography
Assembly:  mscorlib (in mscorlib.dll)

public byte[] ComputeHash(
	Stream inputStream


Type: System.IO.Stream

The input to compute the hash code for.

Return Value

Type: System.Byte[]

The computed hash code.

Exception Condition

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

    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;
                Console.WriteLine("No directory selected.");
            directory = args[0];
            // 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.
                // Close the file.
        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(" ");

.NET Framework
Available since 1.1
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Return to top