Thursday, 2 April 2015

How to read file from request object



Reading files from request object


using System.IO.Abstractions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace Helper.Utility
{
    public class UploadFile
    {
        private readonly IFileSystem _fileSystem;

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

        public Task<IEnumerable<string>> SaveTransferedFile(HttpRequestMessage request, string filePath)
        {
            var streamProvider = new MultipartFormDataStreamProvider(filePath);
            var task = request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
            {
                var fileInfo = streamProvider.FileData.Select(i =>
                {
                    var disposition = i.Headers.ContentDisposition;
                    string newFileName = disposition.FileName;
                    newFileName = newFileName.Split('\\')[newFileName.Split('\\').Length - 1].Replace("\"",
                        string.Empty);
                    newFileName = Path.Combine(filePath, newFileName);
                    try
                    {
                        if (_fileSystem.File.Exists(newFileName))
                            _fileSystem.File.Delete(newFileName);

                        _fileSystem.File.Move(i.LocalFileName, newFileName);
                    }
                    catch (Exception ex)
                    {
                        //SsiLogger.Logger.Error("File {0} renaming failed {1} ", i.LocalFileName, ex.Message);
                        throw;
                    }
                    return (true).ToString();
                });
                return fileInfo;
            });
            return task;
        }
    }

}

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;
            }
        }
    }
}