stavros-s
2/19/2013 - 12:58 PM

File hash calculator

File hash calculator

private static byte[]
            ComputeFileHash
            (string filename)
        {

            try
            {

                Stream input
                    = File.OpenRead
                    (filename);

                byte[] result 
                    = ComputeFileHash(input);

                return result;
            }
            catch(Exception e)
            {

                Debugger.LogMessageToFile
                    ("An error occured while" +
                     " attempting to compute video hash." +
                     " The error was: " + e );

                return null;
            }

        }

        private static byte[] ComputeFileHash(Stream input)
        {
            long streamsize = input.Length;
            long lhash = streamsize;

            long i = 0;

            var buffer
                = new byte[sizeof(long)];

            while (i < 65536 / sizeof(long)
                && (input.Read(buffer, 0, sizeof(long)) > 0))
            {

                i++;
                lhash +=
                    BitConverter.ToInt64
                    (buffer, 0);
            
            }

            input.Position = Math.Max(0, streamsize - 65536);
            i = 0;
            
            while (i < 65536 / sizeof(long)
                && (input.Read(buffer, 0, sizeof(long)) > 0))
            {

                i++;
                lhash += BitConverter.ToInt64(buffer, 0);

            }

            input.Close();

            byte[] result
                = BitConverter
                .GetBytes(lhash);

            Array.Reverse(result);
            
            return result;
        }