Thursday, 2 April 2015

How to calculate checksum using fileStream object in dotnet




Calculate checksum using fileStream object in dotnet


using System;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.IO.Abstractions;

namespace Helper.Utility
{

//Class CrcUtil.cs used get filestream using filepath for calculating checksum

    public class CrcUtil
    {
        private readonly IFileSystem _fileSystem;

        public CrcUtil(IFileSystem fileSystem)
        {
            _fileSystem = fileSystem;
        }

        public string GetCrcCode(string filePath)
        {
            try
            {
                using (var stream = _fileSystem.File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    return GetCrcCode(stream);
                }
            }
            catch (Exception ex)
            {
                // SsiLogger.Logger.Error("Exception occured in CrcUtil {0} for file {1}", ex.Message, filePath);
                // SsiLogger.Logger.Debug(ex);
                throw;
            }
        }

        public string GetCrcCode(Stream fileStream)
        {
            try
            {
                return Md5HashGenerator.GenerateKey(fileStream);
            }
            catch (Exception ex)
            {
                // SsiLogger.Logger.Error("Exception occured in CrcUtil {0}", ex.Message);
                // SsiLogger.Logger.Debug(ex);
                throw;
            }
        }
    }
//Class Md5HashGenerator.cs used for calculating checksum of passed filestream

    public class Md5HashGenerator
    {
        public static String GenerateKey(Stream sourceObject)
        {
            //Catch unuseful parameter values
            if (sourceObject == null)
            {
                throw new ArgumentNullException("sourceObject");
            }
            //We determine if the passed object is really serializable.
            try
            {
                //Now we begin to do the real work.
                var hashString = ComputeHash(sourceObject);
                return hashString;
            }
            catch (AmbiguousMatchException ame)
            {
                throw new ApplicationException(string.Format("Could not definitly decide if object is serializable. Message:{0}", ame.Message));
            }
            catch (Exception ex)
            {
                // SsiLogger.Logger.Error("Exception occured in Md5HashGenerator {0}", ex.Message);
                // SsiLogger.Logger.Debug(ex);
                throw;
            }

        }

        private static string ComputeHash(Stream objectAsBytes)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            try
            {
                var result = md5.ComputeHash(objectAsBytes);
                // Build the final string by converting each byte
                // into hex and appending it to a StringBuilder
                var stringBuilder = new StringBuilder();
                foreach (var data in result)
                {
                    stringBuilder.Append(data.ToString("X2"));
                }

                // And return it
                return stringBuilder.ToString();
            }
            catch (ArgumentNullException)
            {
                //If something occured during serialization, this method is called with an null argument.
                // SsiLogger.Logger.Error("Hash has not been generated.");
                return null;
            }
            catch (Exception ex)
            {
                // SsiLogger.Logger.Error("Exception occured in Md5HashGenerator {0}", ex.Message);
                // SsiLogger.Logger.Debug(ex);
                throw;
            }
        }
    }
}


No comments:

Post a Comment