這篇文章將為大家詳細(xì)講解有關(guān)如何在asp.NET中都文件進(jìn)行壓縮和解壓,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
成都創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),武鄉(xiāng)企業(yè)網(wǎng)站建設(shè),武鄉(xiāng)品牌網(wǎng)站建設(shè),網(wǎng)站定制,武鄉(xiāng)網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營(yíng)銷,網(wǎng)絡(luò)優(yōu)化,武鄉(xiāng)網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長(zhǎng)自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。一、使用System.IO.Packaging壓縮和解壓
Package為一個(gè)抽象類,可用于將對(duì)象組織到定義的物理格式的單個(gè)實(shí)體中,從而實(shí)現(xiàn)可移植性與高效訪問(wèn)。ZIP 文件是Package的主物理格式。 其他Package實(shí)現(xiàn)可以使用其他物理格式(如 XML 文檔、數(shù)據(jù)庫(kù)或 Web 服務(wù)。與文件系統(tǒng)類似,在分層組織的文件夾和文件中引用 Package 中包含的項(xiàng)。雖然 Package 是抽象類,但 Package.Open 方法默認(rèn)使用 ZipPackage 派生類。
System.IO.Packaging在WindowsBase.dll程序集下,使用時(shí)需要添加對(duì)WindowsBase的引用。
1、將整個(gè)文件夾壓縮成zip
/// <summary> /// Add a folder along with its subfolders to a Package /// </summary> /// <param name="folderName">The folder to add</param> /// <param name="compressedFileName">The package to create</param> /// <param name="overrideExisting">Override exsisitng files</param> /// <returns></returns> static bool PackageFolder(string folderName, string compressedFileName, bool overrideExisting) { if (folderName.EndsWith(@"\")) folderName = folderName.Remove(folderName.Length - 1); bool result = false; if (!Directory.Exists(folderName)) { return result; } if (!overrideExisting && File.Exists(compressedFileName)) { return result; } try { using (Package package = Package.Open(compressedFileName, FileMode.Create)) { var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories); foreach (string fileName in fileList) { //The path in the package is all of the subfolders after folderName string pathInPackage; pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName); Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative)); PackagePart packagePartDocument = package.CreatePart(partUriDocument,"", CompressionOption.Maximum); using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { fileStream.CopyTo(packagePartDocument.GetStream()); } } } result = true; } catch (Exception e) { throw new Exception("Error zipping folder " + folderName, e); } return result; }
2、將單個(gè)文件添加到zip文件中
/// <summary> /// Compress a file into a ZIP archive as the container store /// </summary> /// <param name="fileName">The file to compress</param> /// <param name="compressedFileName">The archive file</param> /// <param name="overrideExisting">override existing file</param> /// <returns></returns> static bool PackageFile(string fileName, string compressedFileName, bool overrideExisting) { bool result = false; if (!File.Exists(fileName)) { return result; } if (!overrideExisting && File.Exists(compressedFileName)) { return result; } try { Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(Path.GetFileName(fileName), UriKind.Relative)); using (Package package = Package.Open(compressedFileName, FileMode.OpenOrCreate)) { if (package.PartExists(partUriDocument)) { package.DeletePart(partUriDocument); } PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum); using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { fileStream.CopyTo(packagePartDocument.GetStream()); } } result = true; } catch (Exception e) { throw new Exception("Error zipping file " + fileName, e); } return result; }
3、zip文件解壓
/// <summary> /// Extract a container Zip. NOTE: container must be created as Open Packaging Conventions (OPC) specification /// </summary> /// <param name="folderName">The folder to extract the package to</param> /// <param name="compressedFileName">The package file</param> /// <param name="overrideExisting">override existing files</param> /// <returns></returns> static bool UncompressFile(string folderName, string compressedFileName, bool overrideExisting) { bool result = false; try { if (!File.Exists(compressedFileName)) { return result; } DirectoryInfo directoryInfo = new DirectoryInfo(folderName); if (!directoryInfo.Exists) directoryInfo.Create(); using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read)) { foreach (PackagePart packagePart in package.GetParts()) { ExtractPart(packagePart, folderName, overrideExisting); } } result = true; } catch (Exception e) { throw new Exception("Error unzipping file " + compressedFileName, e); } return result; } static void ExtractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting) { string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', '/'); if (!Directory.Exists(Path.GetDirectoryName(stringPart))) Directory.CreateDirectory(Path.GetDirectoryName(stringPart)); if (!overrideExisting && File.Exists(stringPart)) return; using (FileStream fileStream = new FileStream(stringPart, FileMode.Create)) { packagePart.GetStream().CopyTo(fileStream); } }
使用Package壓縮文件會(huì)在zip文件自動(dòng)生成[Content_Type].xml,用來(lái)描述zip文件解壓支持的文件格式。
<?xml version="1.0" encoding="utf-8" ?> <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"> <Default Extension="vsixmanifest" ContentType="text/xml" /> <Default Extension="dll" ContentType="application/octet-stream" /> <Default Extension="png" ContentType="application/octet-stream" /> <Default Extension="txt" ContentType="text/plain" /> <Default Extension="pkgdef" ContentType="text/plain" /> </Types>
同樣,如果zip文件不包含[Content_Type].xml文件,或者[Content_Type].xml文件不包含所對(duì)應(yīng)擴(kuò)展名的描述(手動(dòng)添加的[Content_Type].xml也是可以),將無(wú)法解壓文件。
二、使用第三方類庫(kù)
zip的壓縮和解壓使用比較的有SharpZipLib和DotNetZip。
1、SharpZipLib,也稱為“#ziplib”,基于GPL開(kāi)源,支持Zip,GZip,Tar和BZip2的壓縮和解壓縮。
支持.NET 1.1,NET 2.0(3.5、4.0).
(1)zip壓縮
public static void Zip(string SrcFile, string DstFile, int BufferSize) { FileStream fileStreamIn = new FileStream (SrcFile, FileMode.Open, FileAccess.Read); FileStream fileStreamOut = new FileStream (DstFile, FileMode.Create, FileAccess.Write); ZipOutputStream zipOutStream = new ZipOutputStream(fileStreamOut); byte[] buffer = new byte<buffersize />; ZipEntry entry = new ZipEntry(Path.GetFileName(SrcFile)); zipOutStream.PutNextEntry(entry); int size; do { size = fileStreamIn.Read(buffer, 0, buffer.Length); zipOutStream.Write(buffer, 0, size); } while (size > 0); zipOutStream.Close(); fileStreamOut.Close(); fileStreamIn.Close(); }
(2)解壓zip
public static void UnZip(string SrcFile, string DstFile, int BufferSize) { FileStream fileStreamIn = new FileStream (SrcFile, FileMode.Open, FileAccess.Read); ZipInputStream zipInStream = new ZipInputStream(fileStreamIn); ZipEntry entry = zipInStream.GetNextEntry(); FileStream fileStreamOut = new FileStream (DstFile + @"\" + entry.Name, FileMode.Create, FileAccess.Write); int size; byte[] buffer = new byte<buffersize />; do { size = zipInStream.Read(buffer, 0, buffer.Length); fileStreamOut.Write(buffer, 0, size); } while (size > 0); zipInStream.Close(); fileStreamOut.Close(); fileStreamIn.Close(); }
2、DotNetLib,是基于”WS-PL”開(kāi)源,使用比較簡(jiǎn)單
(1)壓縮
using (ZipFile zip = new ZipFile()) { zip.AddFile("ReadMe.txt"); zip.AddFile("7440-N49th.png"); zip.AddFile("2008_Annual_Report.pdf"); zip.Save("Archive.zip"); }
(2)解壓
private void MyExtract() { string zipToUnpack = "C1P3SML.zip"; string unpackDirectory = "Extracted Files"; using (ZipFile zip1 = ZipFile.Read(zipToUnpack)) { // here, we extract every entry, but we could extract conditionally // based on entry name, size, date, checkbox status, etc. foreach (ZipEntry e in zip1) { e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently); } } }
三、在.NET 4.5使用ZipArchive、ZipFile等類壓縮和解壓
static void Main(string[] args) { string ZipPath = @"c:\users\exampleuser\start.zip"; string ExtractPath = @"c:\users\exampleuser\extract"; string NewFile = @"c:\users\exampleuser\NewFile.txt"; using (ZipArchive Archive = ZipFile.Open(ZipPath, ZipArchiveMode.Update)) { Archive.CreateEntryFromFile(NewFile, "NewEntry.txt"); Archive.ExtractToDirectory(ExtractPath); } }
關(guān)于如何在asp.NET中都文件進(jìn)行壓縮和解壓就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
本文題目:如何在asp.NET中都文件進(jìn)行壓縮和解壓-創(chuàng)新互聯(lián)
轉(zhuǎn)載注明:http://jinyejixie.com/article48/dcpihp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、企業(yè)建站、標(biāo)簽優(yōu)化、小程序開(kāi)發(fā)、網(wǎng)站設(shè)計(jì)、關(guān)鍵詞優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容