Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Multi-File Packaging and Compression in C #

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

C# how to achieve multi-file packaging and compression, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Recently, the project needs to implement the function of multi-file packaging, tried some methods, and finally found that the use of ICSharpCode.SharpZipLib is most in line with the requirements of the project.

The specific implementation is as follows:

1. Install ICSharpCode.SharpZipLib in Nuget

two。 Put the files to be packaged in the same folder for compression: ① compressed folder / compressed file / the compressed file name public static bool CompressFile (string dir, out string fileName) {string dest = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Desktop) + "\" + string.Format ("{0:yyyyMMddHHmmss}") DateTime.Now) + ".zip" / / default compression on the desktop if (! Directory.Exists (Path.GetDirectoryName (dest) / / create E:\\ test Directory.CreateDirectory (Path.GetDirectoryName (dest)) according to the path if the file does not exist; using (ZipOutputStream zipStream = new ZipOutputStream (File.Create (dest) {zipStream.SetLevel (6) / / Compression level 0-9 CreateZip (dir, zipStream); fileName = dest; zipStream.Finish (); zipStream.Close ();} return true } / compress the content into the zipStream stream / Source file / destination file stream (full path + file name + .zip) private static void CreateZip (string source, ZipOutputStream zipStream) {Crc32 crc = new Crc32 (); string [] files = Directory.GetFileSystemEntries (source) / / get all file names and directory names foreach (var file in files) {if (Directory.Exists (file)) / / Recursive {CreateZip (file, zipStream) if there are files in the folder } else / / if not, compress {using (FileStream fs = File.OpenRead (file)) {byte [] buffer = new byte [fs.Length]; fs.Read (buffer, 0, buffer.Length) String tempFileName = file.Substring (file.LastIndexOf ("\") + 1); / / get the file name of the current file path ZipEntry entry = new ZipEntry (tempFileName); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close () Crc.Reset (); crc.Update (buffer); entry.Crc = crc.Value; zipStream.PutNextEntry (entry); zipStream.Write (buffer, 0, buffer.Length) } ② packages and compresses the specified files (online files can be packaged) / packages online and offline files / file list / save path public static void ZipOnlineFile3 (List fileList) String savepath) {/ / determine whether if (! File.Exists (savepath)) {var file = new FileInfo (savepath) exists in the saved file directory If (! file.Directory.Exists) {file.Directory.Create ();}} Crc32 crc = new Crc32 (); using (ZipOutputStream zipStream = new ZipOutputStream (File.Create (savepath) {zipStream.SetLevel (9) / / Compression level 0-9 foreach (var url in fileList) {byte [] buffer = new WebClient () .DownloadData (url); string tempFileName = GetFileNameByUrl (url); / / get the file name of the current file path ZipEntry entry = new ZipEntry (tempFileName); entry.DateTime = DateTime.Now Entry.Size = buffer.Length; crc.Reset (); crc.Update (buffer); zipStream.PutNextEntry (entry); zipStream.Write (buffer, 0, buffer.Length);}

The method of reading the file name from the file path:

Public static string GetFileNameByUrl (string url) {/ / determine whether the path is empty if (string.IsNullOrWhiteSpace (url)) return null; / / determine whether it is an online file if (url.ToLower (). StartsWith ("http")) {return url.Substring (url.LastIndexOf ("/") + 1) } else {return url.Substring (url.LastIndexOf ("\\") + 1);}}

With the compressed package generated by this method, all files are displayed on the same layer.

③ if you need to create a directory in a file, you need to specify the file path on the file name

Add a tool class:

/ File object / public class FileItem {/ File name / public string FileName {get; set;} / File path / public string FileUrl {get; set;}}

How to compress a file:

/ package online and offline files / compressed file name / / file list / save path public static string ZipFiles (string zipName, List fileList, out string error) {error = string.Empty String path = string.Format ("/ files/zipFiles/ {0} / {1} / {2} /", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); / / File save directory string directory = FileSavePath + path; string url = FileHostUrl.TrimEnd ('/') + path + zipName; string savePath = directory + zipName Try {if (! Directory.Exists (directory)) {Directory.CreateDirectory (directory);} using (ZipOutputStream zipStream = new ZipOutputStream (File.Create (savePath) {zipStream.SetLevel (9) / / Compression level 0-9 foreach (var item in fileList) {byte [] buffer = new WebClient () .DownloadData (item.FileUrl); ZipEntry entry = new ZipEntry (item.FileName); entry.DateTime = DateTime.Now; entry.Size = buffer.Length ZipStream.PutNextEntry (entry); zipStream.Write (buffer, 0, buffer.Length);} catch (Exception ex) {error = "File packaging failed:" + ex.Message;} return url }

Example of calling parameters:

{"zipName": "test.zip", "fileList": [{"fileName": "123.png", "fileUrl": "https://file.yidongcha.cn/files/uploadfiles/image/2021/11/15/11c6de395fcc484faf4745ade62cf6e6.png"}, {" fileName ":" 123/456/789.jpg " "fileUrl": "https://file.yidongcha.cn/files/uploadfiles/image/2021/11/15/fe922b250acf4344b8ca4d2aad6e0355.jpg"}]}

The resulting result:

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report