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

}

No comments:

Post a Comment