栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

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

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

生成Zip代码-no1:

        //Unit Test
        [Test]
        public void GenerationZip()
        {
            //文件生成目录
            string folder = "Template";
            //文件列表
            IList fileNames = new List()
            {
                 //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));
        }

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

        /// 
        ///Byte转File
        /// 
        /// 
        /// 
        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();
        }

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

        /// 
        /// 获取压缩文件的字节信息
        /// 
        /// 
        /// 
        public static byte[] GetZipByte(IList 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;
        }

        /// 
        /// 读取文件的字节数组
        /// 
        /// 
        /// 
        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 fileAddress = new List();
            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:UsersDcDesktopExcel";
            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:

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

                if (filePaths.Count() == 0)
                    return Content("", "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 filePath = new Dictionary();
                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);

            }
        }


        /// 
        /// 压缩多个文件打包
        /// 
        /// 要压缩的文件的路径集合
        /// 每次写入的缓冲区大小
        /// 压缩等级(0-9)
        /// 压缩后路径 
        public static string ZipFile(Dictionary 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;

        }
        /// 
        /// 下载谷歌游览器
        /// 
        /// 
        /// Author   :  today
        /// Date     :  2020-10-18
        /// 
        /// 
        [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);
        }

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908637.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号