c# 創建文件夾、壓縮成zip格式並下載


接到一個需求,需要將圖片及其他數據信息存儲到txt文件下並根據上傳時間分別打包到文件夾內。

需要打包的數據:Img1,img2,updatetime,carcode,address

分析:首先,創建一級文件夾:firstFile,創建二級文件夾:secondFile.

           其次,將carcode,address數據存儲到txt文本內

           第三,將txt文本和img1、img2分別存儲到secondFile文件夾

           第四,壓縮文件並下載

           第五,刪除壓縮包及創建的文件夾

結果:程序根目錄下的Download文件夾內,

     

 

 

代碼:

 

創建一級文件夾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下面即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM