【笔记】.Net 批量压缩下载

此代码为封装的文件操作类,包含 多个文件打包下载,以及文件的基本操作方法。

* 使用压缩文件需要引入DotNetZip包,可通过Nuget 安装

using FLM_API_Public.Helper;
using Ionic.Zip;
using System;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace FLM_API_Public.Utility
{
    /// <summary>
    /// 文件下载
    /// </summary>
    public class FileDownLoad
    {
        //获取配置目录
        //zip保存路径
        public static string ziptempPath = ConfigurationManager.AppSettings["ZipTempPath"];
        //文件列表临时保存路径
        public static string filetempPath = ConfigurationManager.AppSettings["FileTempPath"];

        /// <summary>
        /// 获取单个文件
        /// </summary>
        /// <param name="filesingle">文件信息</param>
        /// <param name="is_compress">是否压缩</param>
        /// <param name="zipfilename">原始文件名或压缩文件名</param>
        /// <returns></returns>
        public static byte[] GetFileSingle(DataTable filesingle, bool is_compress, ref string zipfilename)
        {
            byte[] stream = null;

            //压缩包名:GUID+.zip
            zipfilename = $"{GenerateHelper.NewGuid("NU")}.zip";
            //压缩包文件夹路径
            string zipDirPath = HttpContext.Current.Server.MapPath(ziptempPath);
            //压缩包保存路径
            string zipSavePath = $"{zipDirPath}\\{zipfilename}";
            //临时文件存放目录
            string filedirPath = HttpContext.Current.Server.MapPath($"{filetempPath}/{GenerateHelper.NewGuid("NU")}");

            try
            {
                //源文件地址
                string sourcefilepath = filesingle.Rows[0]["file_phy_path"].ToString();
                string fileRealName = filesingle.Rows[0]["file_name"].ToString();

                //如果文件路径不为空,且文件存在
                if (!string.IsNullOrEmpty(sourcefilepath) && File.Exists(sourcefilepath))
                {
                    if (is_compress)
                    {
                        //创建zip目录
                        CreateDirectory(zipDirPath);
                        //创建文件临时存放目录
                        CreateDirectory(filedirPath);
                        //复制文件到指定目录
                        CopyFile(sourcefilepath, filedirPath + "\\" + fileRealName, true);

                        //文件复制完成,开始打包
                        using (var zip = new ZipFile(Encoding.UTF8))
                        {

                            zip.AddDirectory(filedirPath);
                            zip.Save(zipSavePath);
                        }

                        //打包完成,获取压缩包文件流
                        stream = File.ReadAllBytes(zipSavePath);
                    }
                    else
                    {
                        //如果不压缩,直接返回文件流
                        stream = File.ReadAllBytes(sourcefilepath);
                        //返回真实文件名
                        zipfilename = fileRealName;
                    }

                }
            }
            catch (Exception ex)
            {
                string errormsg = $"文件压缩异常:{ex.Message}";
                LogHelper.Write(errormsg, LogCategory.Error, System.Diagnostics.TraceEventType.Error);
                throw new Exception(errormsg);
            }
            finally
            {
                //下载完成,清理临时目录
                ClearDirectory(filedirPath);
                //删除压缩包
                DeleteFile(zipSavePath);
            }
            return stream;
        }

        /// <summary>
        /// 多个文件打包
        /// </summary>
        /// <param name="Data">文件集合(包括文件路径,文件基本信息等)</param>
        /// <param name="zipfilename">返回的zip文件名</param>
        /// <returns>返回Byte数组</returns>
        public static byte[] GetFileZip(DataTable Data, ref string zipfilename)
        {
            byte[] stream = null;

            //压缩包名:GUID+.zip
            zipfilename = $"{GenerateHelper.NewGuid("NU")}.zip";
            //压缩包文件夹路径
            string zipDirPath = HttpContext.Current.Server.MapPath(ziptempPath);
            //压缩包保存路径
            string zipSavePath = $"{zipDirPath}\\{zipfilename}";
            //文件存放目录
            string filedirPath = HttpContext.Current.Server.MapPath($"{filetempPath}/{GenerateHelper.NewGuid("NU")}");

            try
            {
                //如果数据源不为空,且数量大于0
                if (Data != null && Data.Rows.Count > 0)
                {
                    //创建zip目录
                    CreateDirectory(zipDirPath);
                    //创建文件临时存放目录
                    CreateDirectory(filedirPath);

                    //复制文件
                    foreach (DataRow r in Data.Rows)
                    {
                        //源文件路径
                        string sourcefilepath = r["file_phy_path"].ToString();
                        //真实文件名
                        string fileRealName = r["file_name"].ToString();
                        //复制文件到指定目录
                        CopyFile(sourcefilepath, filedirPath + "\\" + fileRealName, true);
                    }

                    //文件复制完成,开始打包
                    using (var zip = new ZipFile(Encoding.UTF8))
                    {

                        zip.AddDirectory(filedirPath);
                        zip.Save(zipSavePath);
                    }

                    //打包完成,获取压缩包文件流
                    //stream = new FileStream(zipSavePath, FileMode.Open, FileAccess.Read);
                    stream = File.ReadAllBytes(zipSavePath);


                }
            }
            catch (Exception ex)
            {
                string errormsg = $"批量下载文件异常:{ex.Message}";
                LogHelper.Write(errormsg, LogCategory.Error, System.Diagnostics.TraceEventType.Error);
                throw new Exception(errormsg);
            }
            finally
            {

                //下载完成,清理临时目录
                ClearDirectory(filedirPath);
                //删除压缩包
                DeleteFile(zipSavePath);
            }
            return stream;
        }


        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="directoryPath"></param>
        private static void CreateDirectory(string directoryPath)
        {
            try
            {
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }
            }
            catch (Exception ex)
            {
                string errormsg = $"创建目录出现异常:{ex.Message}";
                LogHelper.Write(errormsg, LogCategory.Error, System.Diagnostics.TraceEventType.Error);
                throw new Exception(errormsg);
            }
        }


        /// <summary>
        /// 清空所有文件
        /// </summary>
        /// <param name="directory">文件夹路径</param>
        /// <param name="delFolder">是否删除文件夹(默认true)</param>
        private static void ClearDirectory(string directory, bool delFolder = true)
        {
            try
            {
                //如果目录存在
                if (Directory.Exists(directory))
                {
                    //清空文件夹下所有文件
                    Directory.EnumerateFiles(directory).ToList().ForEach(File.Delete);
                }

                if (delFolder)
                {
                    if (Directory.Exists(directory))
                    {
                        //如果文件夹存在,删除文件夹
                        Directory.Delete(directory);
                    }
                }
            }
            catch (Exception ex)
            {
                string errormsg = $"删除目录出现异常:{ex.Message}";
                LogHelper.Write(errormsg, LogCategory.Error, System.Diagnostics.TraceEventType.Error);
                throw new Exception(errormsg);
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filepath">文件目录</param>
        private static void DeleteFile(string filepath)
        {
            try
            {
                if (File.Exists(filepath))
                {
                    File.Delete(filepath);
                }
            }
            catch (Exception ex)
            {
                string errormsg = $"删除文件异常:{ex.Message}";
                LogHelper.Write(errormsg, LogCategory.Error, System.Diagnostics.TraceEventType.Error);
                throw new Exception(errormsg);
            }
        }



        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="sourceFilePath">源文件路径</param>
        /// <param name="saveFilePath">指定存储路径</param>
        /// <param name="cover">相同目录下,相同文件是否覆盖(默认覆盖)</param>
        private static void CopyFile(string sourceFilePath, string saveFilePath, bool cover)
        {
            try
            {
                //判断文件是否存在
                if (File.Exists(sourceFilePath))
                {
                    //如果存在,复制文件到指定目录
                    File.Copy(sourceFilePath, saveFilePath, cover);
                }
            }
            catch (Exception ex)
            {
                //复制文件异常
                string errormsg = $"文件复制出现异常:{ex.Message}";
                LogHelper.Write(errormsg, LogCategory.Error, System.Diagnostics.TraceEventType.Error);
                throw new Exception(errormsg);
            }
        }
    }

}

猜你喜欢

转载自blog.csdn.net/Csongxuan/article/details/107032807