.net core 操作file、txt、xml文件流

生成Zip代码-no1:

        //Unit Test
        [Test]
        public void GenerationZip()
        {
            //文件生成目录
            string folder = "Template";
            //文件列表
            IList<string> fileNames = new List<string>()
            {
                 //AppDomain.CurrentDomain.BaseDirectory 项目根目录
                 //Path.Combine 拼接参数,可支持windows和liunx查找
                 Path.Combine(AppDomain.CurrentDomain.BaseDirectory,folder,"开发测试Level.xlsx"),
                 Path.Combine(AppDomain.CurrentDomain.BaseDirectory,folder,"开发测试Group.xlsx")
            };

            //zip文件生成目录
            string targetZipFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder, "temp.zip");
            //生成zip文件主方法
            GenerationZip();

            Assert.IsTrue(File.Exists(targetZipFilePath));
        }

        /// <summary>
        /// 生成zip 文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="zipFilePath">zip文件路径</param>
        public static void GenerationZip(IList<string> filePath, string zipFilePath)
        {
            string folder = Path.GetDirectoryName(zipFilePath);
            CreateIfNotExists(folder);
            byte[] byteContent = GetZipByte(filePath);
            if (byteContent.ExistCount())
            {
                ByteToFile(byteContent, zipFilePath);
            }
        }

        /// <summary>
        ///Byte转File
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="filePath"></param>
        public static void ByteToFile(byte[] bytes, string filePath)
        {
            string folder = Path.GetDirectoryName(filePath);
            CreateIfNotExists(folder);
            FileStream fs = new FileStream(filePath, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(bytes);
            bw.Close();
            bw.Dispose();
            fs.Close();
            fs.Dispose();
        }

        /// <summary>
        /// 如果不存在目录则进行创建
        /// </summary>
        /// <param name="path"></param>
        public static void CreateIfNotExists(string path)
        {
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
        }

        /// <summary>
        /// 获取压缩文件的字节信息
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static byte[] GetZipByte(IList<string> filePath)
        {
            if (filePath.ExistCount())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Create))
                    {
                        for (int i = 0; i < filePath.Count; i++)
                        {
                            string item = filePath[i].ToStrAndTrim();

                            if (item.NotNull() && File.Exists(item.ToStrAndTrim()))
                            {
                                ZipArchiveEntry readMeEntry = archive.CreateEntry(Path.GetFileName(item));
                                using (Stream s = readMeEntry.Open())
                                {
                                    byte[] fileBytes = GetBytes(item);
                                    s.Write(fileBytes, 0, fileBytes.Length);
                                }
                            }
                        }
                    }
                    return ms.ToArray();
                }
            }
            return null;
        }

        /// <summary>
        /// 读取文件的字节数组
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static byte[] GetBytes(string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    byte[] buffur = new byte[fs.Length];
                    fs.Read(buffur, 0, (int)fs.Length);
                    return buffur;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    fs?.Close();
                    fs?.Dispose();
                }
            }
        }

浏览器下载Zip代码:

        public async Task DownloadWholeFile()
        {
            //文件目录集合
            List<string> fileAddress = new List<string>();
            fileAddress.Add(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template", "开发测试Level.xlsx"));
            //zip文件目录
            string targetZipFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template","temp.zip");
            //开始生成zip文件
            GenerationZip(fileNames, targetZipFilePath);
            //读取zip文件到数据流
            FileStream fileStream = new FileStream(targetZipFilePath, FileMode.Open, FileAccess.Read);
            HttpContext.Response.StatusCode = StatusCodes.Status200OK;
            var stream = HttpContext.Response.Body;
            await fileStream.CopyToAsync(stream);
            await stream.FlushAsync();
        }

支持浏览器下载excel、txt....通用代码:

        public IActionResult DownloadFile()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "文件路径");
            FileStream fileStream = new FileStream(path, FileMode.Open);
            return File(fileStream, ContentType(path), "下载完成后的文件名称");
        }

        public static string ContentType(string TemplateName)
        {
            string fileExt = Path.GetExtension(TemplateName);
            //获取文件的ContentType
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            var memi = provider.Mappings[fileExt] ?? "";
            return memi;
        }

指定文件夹的所有内容读取为Stream并生成压缩包输出到浏览器:

        [HttpGet]
        public async Task Get()
        {
            var folder = @"C:\Users\Dc\Desktop\Excel";
            HttpContext.Response.StatusCode = StatusCodes.Status200OK;

            var stream = HttpContext.Response.Body;

            await ReadDirectoryToZipStreamAsync(new DirectoryInfo(folder), stream);
        }

         public static async Task ReadDirectoryToZipStreamAsync(DirectoryInfo directory, Stream stream)
        {
            //获取指定文件夹下面的全部文件
            var fileList = directory.GetFiles();

            var zipArchive = new ZipArchive(stream, ZipArchiveMode.Create);
            foreach (var file in fileList)
            {
                var relativePath = file.FullName.Replace(directory.FullName, "");
                if (relativePath.StartsWith("\\") || relativePath.StartsWith("//"))
                {
	                //文件名称
                    relativePath = relativePath.Substring(1);
                }
                ZipArchiveEntry zipArchiveEntry = zipArchive.CreateEntry(relativePath, CompressionLevel.NoCompression);

                using (var entryStream = zipArchiveEntry.Open())
                {
                    var toZipStream = file.OpenRead();
                    await toZipStream.CopyToAsync(stream);
                }

                await stream.FlushAsync();
            }
        }

no2:

         /// <summary>
        /// 下载附件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DownloadAttachment()
        {
            try
            {
                //文件集合,key:文件名称  value:文件路径
                Dictionary<string, string> filePaths = new Dictionary<string, string>();

                if (filePaths.Count() == 0)
                    return Content("<script>alert('无附件可导出');history.go(-1);</script>", "text/html");
                if (filePaths.Count() == 1)
                {
                    var obj = filePaths.FirstOrDefault();
                    FileStream fs = new FileStream(obj.Value, FileMode.Open);
                    return File(fs, new FileExtensionContentTypeProvider().Mappings[".xlsx"] ?? "", "原始文件名称");
                }
                Dictionary<string, string> filePath = new Dictionary<string, string>();
                foreach (var item in filePaths)
                {
                    if (filePath.ContainsKey(item.Key))
                        filePath.Add(item.Key + "-1", item.Value);
                    else
                        filePath.Add(item.Key, item.Value);
                }
                string newFilePath = ZipFile(filePath);
                FileStream stream = new FileStream(newFilePath, FileMode.Open);
                return File(stream, new FileExtensionContentTypeProvider().Mappings[".zip"] ?? "", DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip");
            }
            catch (Exception e)
            {
                return Content(e.Message);

            }
        }


        /// <summary>
        /// 压缩多个文件打包
        /// </summary>
        /// <param name="filesToZip">要压缩的文件的路径集合</param>
        /// <param name="blockSize">每次写入的缓冲区大小</param>
        /// <param name="zipLevel">压缩等级(0-9)</param>
        /// <returns>压缩后路径</returns> 
        public static string ZipFile(Dictionary<string,string> filesToZip, int blockSize = 2048, int zipLevel = 9)
        {
            var folderNamePath = Path.Combine(FileHelper.AttachmentPath, "TempFile");
            if (!Directory.Exists(folderNamePath))
            {
                Directory.CreateDirectory(folderNamePath);
            }
            //压缩后的压缩文件相对路径
            var newFileName = Path.Combine(folderNamePath, DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".zip");

            //创建压缩文件
            ZipOutputStream zipStream = new ZipOutputStream(File.Create(newFileName));
            zipStream.SetLevel(zipLevel);


            //写入所有文件到压缩文件
            foreach (var item in filesToZip)
            {
                FileStream fs = null;
                try
                {
                    //被压缩的文件名
                    string strFileName = item.Key;

                    ZipEntry entry = new ZipEntry(strFileName);
                    entry.DateTime = DateTime.Now;
                    zipStream.PutNextEntry(entry);

                    //读取文件
                    fs = File.OpenRead(item.Value);

                    //缓冲区大小
                    byte[] buffer = new byte[blockSize];
                    int sizeRead = 0;
                    do
                    {
                        sizeRead = fs.Read(buffer, 0, buffer.Length);
                        zipStream.Write(buffer, 0, sizeRead);
                    }
                    while (sizeRead > 0);
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                        fs.Dispose();
                    }
                }
            }
            zipStream.Finish();
            zipStream.Close();

            //返回压缩后的压缩文件相对路径
            return newFileName;

        }
        /// <summary>
        /// 下载谷歌游览器
        /// </summary>
        /// <remark>
        /// <para/>Author   :  today
        /// <para/>Date     :  2020-10-18
        /// </remark>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult DownloadChrome()
        {
            string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Setup", "ChromeSetup.exe");
            System.IO.FileInfo file = new System.IO.FileInfo(path);
            byte[] bytes = null;
            using (var fs = file.OpenRead())
            {
                fs.Position = 0;
                bytes = new byte[fs.Length];
                fs.Read(bytes, 0, bytes.Length);
            }
            return File(bytes, "application/x-msdownload", file.Name);
        }

如果对你有帮助,就点个赞吧!你的肯定是最大的支持!!!

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值