コード例 #1
0
    /// <summary>
    /// Saves uploaded IFormFile files to physical file path. If file list is null or empty returns empty <see cref="List{String}"/>
    /// Target Path will be : "<paramref name ="basePath"></paramref>/<b><paramref name="folderNameCreator"/>()</b>/<paramref name="entity"></paramref>.<paramref name="propertyName"/>"
    /// </summary>
    ///
    /// <para><b>Remarks:</b></para>
    ///
    /// <remarks>
    ///
    /// <para> Don't forget validate files with <see cref="ValidateFile(IFormFile, long, List{string}, FileType)"/>, before use this method.</para>
    ///
    /// </remarks>
    ///
    /// <typeparam name="TEntity"></typeparam>
    /// <typeparam name="TFileDTO"></typeparam>
    /// <typeparam name="TFileEntity"></typeparam>
    /// <param name="fileDTOList"> Uploaded file in entity. </param>
    /// <param name="entity"></param>
    /// <param name="basePath"></param>
    /// <param name="folderNameCreator"></param>
    /// <param name="propertyName"></param>
    /// <returns> Completed Task </returns>
    public static async Task <List <TFileEntity> > SaveFilesToPathAsync <TEntity, TFileDTO, TFileEntity>(this List <TFileDTO> fileDTOList,
                                                                                                         TEntity entity,
                                                                                                         string basePath,
                                                                                                         FilesFolderNameCreator folderNameCreator,
                                                                                                         string propertyName)
        where TFileDTO : class, IFileDTO
        where TFileEntity : class, IFileEntity, new()
    {
        if (fileDTOList.IsNullOrEmpty())
        {
            return(new List <TFileEntity>());
        }

        var fileEntities = new List <TFileEntity>();

        foreach (var fileDTO in fileDTOList)
        {
            if (fileDTO == null)
            {
                continue;
            }

            var file = fileDTO.File;

            if (file.Length <= 0)
            {
                continue;
            }

            var path = await file.SaveFileToPathAsync(entity, basePath, folderNameCreator, propertyName).ConfigureAwait(false);

            if (!string.IsNullOrWhiteSpace(path))
            {
                fileEntities.Add(new TFileEntity
                {
                    FileName = fileDTO.FileName,
                    FilePath = path
                });
            }
        }

        return(fileEntities);
    }
コード例 #2
0
    /// <summary>
    /// Saves uploaded IFormFile file to physical file path. If <paramref name="file"/>.Lenght is lower or equal than 0 then returns empty string.
    /// Target Path will be : "<paramref name ="basePath"></paramref>/<b><paramref name="folderNameCreator"/>()</b>/<paramref name="entity"></paramref>.<paramref name="propertyName"/>"
    /// </summary>
    ///
    /// <para><b>Remarks:</b></para>
    ///
    /// <remarks>
    ///
    /// <para> Don't forget validate file with <see cref="ValidateFile(IFormFile, long, List{string}, FileType)"/>, before use this method.</para>
    ///
    /// </remarks>
    ///
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="file"> Uploaded file in entity. </param>
    /// <param name="entity"></param>
    /// <param name="basePath"></param>
    /// <param name="folderNameCreator"></param>
    /// <param name="propertyName"></param>
    /// <returns> Completed Task </returns>
    public static async Task <string> SaveFileToPathAsync <TEntity>(this IFormFile file,
                                                                    TEntity entity,
                                                                    string basePath,
                                                                    FilesFolderNameCreator folderNameCreator,
                                                                    string propertyName)
    {
        if (file.Length <= 0)
        {
            return("");
        }

        //Gets file extension.
        var fileExtension = Path.GetExtension(file.FileName);

        //Gets the class name. E.g. If class is ProductDTO then sets the value of this variable as "Product".
        var folderNameOfClass = folderNameCreator.Invoke(entity.GetType());

        //We combined the name of this class (folderNameOfClass) with the path of the basePath folder. So we created the path of the folder belonging to this class.
        var folderPathOfClass = Path.Combine(basePath, folderNameOfClass);

        //If there is no such folder in this path (folderPathOfClass), we created it.
        if (!Directory.Exists(folderPathOfClass))
        {
            Directory.CreateDirectory(folderPathOfClass);
        }

        //Since each data belonging to this class (folderNameOfClass) will have a separate folder, we received the Id of the data sent.
        var folderNameOfItem = CommonHelper.PropertyExists <TEntity>(propertyName)
                                ? entity.GetType().GetProperty(propertyName).GetValue(entity, null).ToString()
                                : throw new MilvaDeveloperException("PropertyNotExists");

        //We created the path to the folder of this Id (folderNameOfItem).
        var folderPathOfItem = Path.Combine(folderPathOfClass, folderNameOfItem);

        try
        {
            //If there is no such folder in this path (folderPathOfItem), we created it.
            if (!Directory.Exists(folderPathOfItem))
            {
                Directory.CreateDirectory(folderPathOfItem);
            }
            else
            {
                Directory.Delete(folderPathOfItem, true);
                Directory.CreateDirectory(folderPathOfItem);
            }
            var fileNameWithExtension = $"{folderNameOfItem}{fileExtension}";
            var filePathOfItem        = Path.Combine(folderPathOfItem, fileNameWithExtension);
            using (var fileStream = new FileStream(filePathOfItem, FileMode.Create))
            {
                await file.CopyToAsync(fileStream).ConfigureAwait(false);
            }

            return(filePathOfItem);
        }
        catch (Exception)
        {
            Directory.Delete(folderPathOfItem, true);
            throw;
        }
    }
コード例 #3
0
    /// <summary>
    /// Saves uploaded IFormFile files to physical file path. If file list is null or empty returns empty <see cref="List{String}"/>
    /// Target Path will be : "<paramref name ="basePath"></paramref>/<b><paramref name="folderNameCreator"/>()</b>/<paramref name="entity"></paramref>.<paramref name="propertyName"/>"
    /// </summary>
    ///
    /// <para><b>Remarks:</b></para>
    ///
    /// <remarks>
    ///
    /// <para> Don't forget validate files with <see cref="ValidateFile(IFormFile, long, List{string}, FileType)"/>, before use this method.</para>
    ///
    /// </remarks>
    ///
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="files"> Uploaded file in entity. </param>
    /// <param name="entity"></param>
    /// <param name="basePath"></param>
    /// <param name="folderNameCreator"></param>
    /// <param name="propertyName"></param>
    /// <returns> Completed Task </returns>
    public static async Task <List <string> > SaveFilesToPathAsync <TEntity>(this IFormFileCollection files,
                                                                             TEntity entity,
                                                                             string basePath,
                                                                             FilesFolderNameCreator folderNameCreator,
                                                                             string propertyName)
    {
        if (files.IsNullOrEmpty())
        {
            return(new List <string>());
        }

        //Gets file extension.
        var fileExtension = Path.GetExtension(files[0].FileName);

        //Gets the class name. E.g. If class is ProductDTO then sets the value of this variable as "Product".
        var folderNameOfClass = folderNameCreator.Invoke(entity.GetType());

        //We combined the name of this class (folderNameOfClass) with the path of the basePath folder. So we created the path of the folder belonging to this class.
        var folderPathOfClass = Path.Combine(basePath, folderNameOfClass);

        //Since each data belonging to this class (folderNameOfClass) will have a separate folder, we received the Id of the data sent.
        var folderNameOfItem = CommonHelper.PropertyExists <TEntity>(propertyName)
                                ? entity.GetType().GetProperty(propertyName).GetValue(entity, null).ToString()
                                : throw new MilvaDeveloperException("PropertyNotExists");

        //We created the path to the folder of this Id (folderNameOfItem).
        var folderPathOfItem = Path.Combine(folderPathOfClass, folderNameOfItem);

        try
        {
            //If there is no such folder in this path (folderPathOfClass), we created it.
            if (!Directory.Exists(folderPathOfClass))
            {
                Directory.CreateDirectory(folderPathOfClass);
            }

            //If there is no such folder in this path (folderPathOfItem), we created it.
            if (!Directory.Exists(folderPathOfItem))
            {
                Directory.CreateDirectory(folderPathOfItem);
            }

            DirectoryInfo directory = new(folderPathOfItem);

            var directoryFiles = directory.GetFiles();

            int markerNo = directoryFiles.IsNullOrEmpty()
                            ? 1
                            : (directoryFiles.Max(fileInDir => Convert.ToInt32(Path.GetFileNameWithoutExtension(fileInDir.FullName).Split('_')[1])) + 1);

            var folderPaths = new List <string>();

            foreach (var item in files)
            {
                var fileNameWithExtension = $"{folderNameOfItem}_{markerNo}{fileExtension}";
                var filePathOfItem        = Path.Combine(folderPathOfItem, fileNameWithExtension);
                using (var fileStream = new FileStream(filePathOfItem, FileMode.Create))
                {
                    await item.CopyToAsync(fileStream).ConfigureAwait(false);
                }
                folderPaths.Add(filePathOfItem);
                markerNo++;
            }

            return(folderPaths);
        }
        catch (Exception)
        {
            Directory.Delete(folderPathOfClass);
            Directory.Delete(folderPathOfItem);
            throw;
        }
    }