c# 创建文件夹、压缩成zip格式并下载

2021/7/30 9:36:16

本文主要是介绍c# 创建文件夹、压缩成zip格式并下载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

接到一个需求,需要将图片及其他数据信息存储到txt文件下并根据上传时间分别打包到文件夹内。

需要打包的数据:Img1,img2,updatetime,carcode,address

分析:首先,创建一级文件夹:firstFile,创建二级文件夹:secondFile.

           其次,将carcode,address数据存储到txt文本内

           第三,将txt文本和img1、img2分别存储到secondFile文件夹

           第四,压缩文件并下载

           第五,删除压缩包及创建的文件夹

代码:

 

创建一级文件夹FirstFile
 
public string FirstCreate(string dt)
        {
            string path = @System.AppDomain.CurrentDomain.BaseDirectory + @"Download/记录_" + dt;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }
创建二级文件夹 secondFile

public string SecondCreate(string path,string vdt, string CarNo)
        {
            string dt = DateTime.Now.ToString("yyyyMMddHHmmss");
            vdt = DateTime.Parse(vdt).ToString("yyyyMMddHHmmss");
            string filname = path + "\\" + vdt + "_" + CarNo;
            if (!Directory.Exists(filname))
            {
                Directory.CreateDirectory(filname);
            }
            return filname;
        }

 

将数据存入到txt文件中

        public bool txtData(string path, string bianhao, string carcode, string carcolor, string cartype, string codecolor, string violationtime, string violationaddr, string x, string y)
        {
            string filename = path + "\\" + carcode + ".txt";//这是地址
            string Text = "编号:" + bianhao + "\r\n" +"车辆牌号:" + carcode + "\r\n" +"地点:" + violationaddr ;
            FileStream fs = new FileStream(filename, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs, Encoding.Unicode);
            sw.Write(Text);
            sw.Close();
            fs.Close();
            return true;
        }

图片在数据库中存储的未URL,所以需要根据图片地址下载图片到本地磁盘


        /// <summary>
        /// 从图片地址下载图片到本地磁盘
        /// </summary>
        /// <param name="ToLocalPath">图片本地磁盘地址</param>
        /// <param name="Url">图片网址</param>
        /// <returns></returns>
        public bool SavePhotoFromUrl(string FileName, string Url)
        {
            bool Value = false;
            WebResponse response = null;
            Stream stream = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                response = request.GetResponse();
                stream = response.GetResponseStream();

                if (!response.ContentType.ToLower().StartsWith("text/"))
                {
                    Value = SaveBinaryFile(response, FileName);
                }
                //stream.Close();
                
            }
            catch (Exception err)
            {
                string aa = err.ToString();
            }
            return Value;
        }
        /// <summary>
        /// Save a binary file to disk.
        /// </summary>
        /// <param name="response">The response used to save the file</param>
        // 将二进制文件保存到磁盘
        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool Value = true;
            byte[] buffer = new byte[1024];
            try
            {
                //if (File.Exists(FileName))
                //    File.Delete(FileName);
                //Stream outStream = System.IO.File.Create(FileName+"\\"+ carcode+".jpg");
                Stream outStream = System.IO.File.Create(FileName);
                Stream inStream = response.GetResponseStream();

                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0)
                        outStream.Write(buffer, 0, l);
                }
                while (l > 0);

                //outStream.Flush();
                outStream.Close();
                //inStream.Flush();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }

  

压缩文件
此处需要引用:

using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;


/// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="sourceFilePath">待拷贝文件或文件夹 绝对路径</param>
        /// <param name="destinationZipFilePath"> 生成zip文件的绝对路径 </param>
        public void CreateZip(string sourceFilePath, string destinationZipFilePath)
        {
            if (sourceFilePath[sourceFilePath.Length - 1] != Path.DirectorySeparatorChar)
                sourceFilePath += Path.DirectorySeparatorChar;
            ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));
            zipStream.SetLevel(6);  // 压缩级别 0-9
            CreateZipFiles(sourceFilePath, zipStream, sourceFilePath);

            zipStream.Finish();
            zipStream.Close();
        }

        /// <summary>
        /// 递归压缩文件
        /// </summary>
        /// <param name="sourceFilePath">待压缩的文件或文件夹路径</param>
        /// <param name="zipStream">打包结果的zip文件路径(类似 D:\WorkSpace\a.zip),全路径包括文件名和.zip扩展名</param>
        /// <param name="staticFile"></param>
        public void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile)
        {
            if (sourceFilePath[sourceFilePath.Length - 1] != Path.DirectorySeparatorChar)
                sourceFilePath += Path.DirectorySeparatorChar;
            Crc32 crc = new Crc32();
            string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
            foreach (string file in filesArray)
            {
                if (Directory.Exists(file))                     //如果当前是文件夹,递归
                {
                    CreateZipFiles(file, zipStream, staticFile);
                }
                else//如果是文件,开始压缩
                {
                    FileStream fileStream = File.OpenRead(file);

                    byte[] buffer = new byte[fileStream.Length];
                    fileStream.Read(buffer, 0, buffer.Length);
                    string tempFile = file.Substring(staticFile.LastIndexOf("\\") + 1);
                    ZipEntry entry = new ZipEntry(tempFile);

                    entry.DateTime = DateTime.Now;
                    entry.Size = fileStream.Length;
                    fileStream.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    zipStream.PutNextEntry(entry);

                    zipStream.Write(buffer, 0, buffer.Length);
                    //zipStream.Flush();
                    //zipStream.Close();

                }
            }
        }

  

下载文件(在控制器中写)

public void OutPutZipFile(HttpContext context, string fileName)
        {
            //客户端保存的文件名 
            string zipname = fileName;
            //目标文件路径
            string filePath = Server.MapPath("~/Download/" + fileName + "");
            //Console.WriteLine(filePath);
            FileInfo fileInfo = new FileInfo(filePath);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();// "attachment;filename=" + HttpUtility.UrlEncode(Encoding.GetEncoding(65001).GetBytes(name))
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Encoding.GetEncoding(65001).GetBytes(zipname)));
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Range", "bytes 0-" + (fileInfo.Length - 1) + "/" + fileInfo.Length);
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = Encoding.GetEncoding("gb2312");
            Response.Flush();
            //文件发送到客户端
            Response.WriteFile(fileInfo.FullName); 
            Response.End();
            Response.Close();
            //string zipName = "违法停车.zip";
            //string filePath = Server.MapPath("~/Download/" + fileName + "");
            ////string filePath = Base_Dir + "\\" + fileName;
            //FileStream fs = new FileStream(filePath, FileMode.Open);//使用字节流的方式打开
            //byte[] bytes = new byte[(int)fs.Length];
            //fs.Read(bytes, 0, bytes.Length);
            //fs.Close();
            //Response.ContentType = "application/octet-stream";
            //Response.AddHeader("Title", fileName);
            ////通知浏览器下载文件而不是打开
            //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipName, System.Text.Encoding.UTF8));
            //Response.BinaryWrite(bytes);
            //Response.Flush();
            //Response.End();
        }

  

 删除文件,此处有些麻烦,会有更好的解决方式

//删除文件夹
        public void DelectDir(string srcPath)
        {
            if (File.Exists(srcPath))
            {
                // 2、根据路径字符串判断是文件还是文件夹
                FileAttributes attr = File.GetAttributes(srcPath);
                // 3、根据具体类型进行删除
                if (attr == FileAttributes.Directory)
                {
                    // 3.1、删除文件夹
                    Directory.Delete(srcPath, true);
                }
                else
                {
                    // 3.2、删除文件
                    File.Delete(srcPath);
                }
                File.Delete(srcPath);
            }
        }

        //删除download文件夹下的所有子文件,删除zip文件
        public void DeleteDir(string file)
        {
            try
            {
                //去除文件夹和子文件的只读属性
                //去除文件夹的只读属性
                DirectoryInfo fileInfo = new DirectoryInfo(file);
                fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;

                //去除文件的只读属性
                File.SetAttributes(file, FileAttributes.Normal);

                //判断文件夹是否还存在
                if (Directory.Exists(file))
                {
                    foreach (string f in Directory.GetFileSystemEntries(file))
                    {
                        if (File.Exists(f))
                        {
                            //如果有子文件删除文件
                            File.Delete(f);
                            Console.WriteLine(f);
                        }
                        else
                        {
                            //循环递归删除子文件夹
                            DeleteDir(f);
                        }
                    }
                    //删除空文件夹
                    Directory.Delete(file);
                }
            }
            catch (Exception ex) // 异常处理
            {
                Console.WriteLine(ex.Message.ToString());// 异常信息
            }
        }

  

代码调用

using System.Data;
using System.Text;
using System.IO;

using System.Text;

using System.Web;

获取需要打包的数据
DataTable table = new DataTable();
string str="select img1,img2,carcode,address,updatetime from table";
table = this.BaseRepository().FindTable(str.ToString());
//创建一级菜单,目录为~Download/记录_202107300902 
string dt = DateTime.Now.ToString("yyyyMMddHHmmss"); 
string firstPath = df.FirstCreate(dt);
foreach (DataRow dr in table.Rows)
{
   string carcode = dr["carcode"].ToString();
   string carcode = dr["address"].ToString();
   string carcode = dr["img1"].ToString();
   string carcode = dr["img2"].ToString();

   //创建二级菜单,并将url地址图片存放到二级菜单中

        string TheFolder = df.SecondCreate(firstPath, updatetime, carcode);
        //图片地址
        string Img1 = TheFolder + "\\" + carcode + "_1.jpg";
        string Img2 = TheFolder + "\\" + carcode + "_2.jpg";
        //图片下载到子文件夹中
        SavePhotoFromUrl(Img1, img1Url);
        SavePhotoFromUrl(Img2, img2Url);

        //将其他数据存储到txt文件中

         txtData(TheFolder,carcode,address,updatetime);

}

//待压缩的文件或文件夹路径路径+文件名称
string ZipFilePath = @System.AppDomain.CurrentDomain.BaseDirectory + @"Download /记录_" + FirstFileName + ".zip";
CreateZip(firstPath, ZipFilePath);

//下载文件

this.OutPutZipFile(Request.RequestContext.HttpContext.ApplicationInstance.Context, zipName);//调用方式

//删除文件

string destFilePath = @System.AppDomain.CurrentDomain.BaseDirectory + @"Download/记录_" + FirstFileName ;
DeleteDir(destFilePath);
string Path = @System.AppDomain.CurrentDomain.BaseDirectory + @"Download/记录_" + FirstFileName + ".zip";
DelectDir(Path);

  

 

       注意: 

 1、添加引用CSharpCode.SharpZipLib.dll ,此处引用的版本为:0.85.4.369。

      引用0.85.4.369版本的dll从服务器上下载解压没有问题,但是添加了0.86.0.518版本,从服务器上下载下来后解压提示图片文件头损坏。【此处巨坑。。。。。。】

添加引用的方式(vs2017):

工具——NuGet包管理器——管理解决方案的NuGet程序包

 

 

2、添加后,运行代码,可能会报出【未能加载文件或程序集“ICSharpCode.SharpZipLib”或它的某一个依赖项】这种错误,

     解决方式:将ICSharpCode.SharpZipLib.dll 复制到web下的bin下面即可。

 



这篇关于c# 创建文件夹、压缩成zip格式并下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程