ASP.NET 파일 압축 해제 클래스(C\#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using System.Web;
namespace Mvc51Hiring.Common.Tool
{
/// <summary> <br> /// : <br> /// :sunkaixaun
///
/// </summary>
public class ZipClass
{
/// <summary>
///
/// </summary>
List<string> files = new List<string>();
/// <summary>
///
/// </summary>
List<string> paths = new List<string>();
/// <summary>
///
/// </summary>
/// <param name="fileToZip"> </param>
/// <param name="zipedFile"> </param>
/// <param name="compressionLevel"> , 0-9, , </param>
/// <param name="blockSize"> </param>
public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
{
if (!System.IO.File.Exists(fileToZip))// ,
{
throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");
}
FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
FileStream zipFile = File.Create(zipedFile);
ZipOutputStream zipStream = new ZipOutputStream(zipFile);
ZipEntry zipEntry = new ZipEntry(fileToZip);
zipStream.PutNextEntry(zipEntry);
zipStream.SetLevel(compressionLevel);
byte[] buffer = new byte[blockSize];
int size = streamToZip.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, size);
try
{
while (size < streamToZip.Length)
{
int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, sizeRead);
size += sizeRead;
}
}
catch (Exception ex)
{
GC.Collect();
throw ex;
}
zipStream.Finish();
zipStream.Close();
streamToZip.Close();
GC.Collect();
}
/// <summary>
/// ( )
/// </summary>
/// <param name="rootPath"> </param>
/// <param name="destinationPath"> </param>
/// <param name="compressLevel"> , 0-9, , </param>
public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)
{
GetAllDirectories(rootPath);
/* while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)// "\"
{
rootPath = rootPath.Substring(0, rootPath.Length - 1);// "\"
}
*/
//string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);// , 。
string rootMark = rootPath + "\\";// , 。
Crc32 crc = new Crc32();
ZipOutputStream outPutStream = new ZipOutputStream(File.Create(destinationPath));
outPutStream.SetLevel(compressLevel); // 0 - store only to 9 - means best compression
foreach (string file in files)
{
FileStream fileStream = File.OpenRead(file);//
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));
entry.DateTime = DateTime.Now;
// set Size and the crc, because the information
// about the size and crc should be stored in the header
// if it is not set it is automatically written in the footer.
// (in this case size == crc == -1 in the header)
// Some ZIP programs have problems with zip files that don't store
// the size and crc in the header.
entry.Size = fileStream.Length;
fileStream.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
outPutStream.PutNextEntry(entry);
outPutStream.Write(buffer, 0, buffer.Length);
}
this.files.Clear();
foreach (string emptyPath in paths)
{
ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "/");
outPutStream.PutNextEntry(entry);
}
this.paths.Clear();
outPutStream.Finish();
outPutStream.Close();
GC.Collect();
}
/// <summary>
///
/// </summary>
public void DwonloadZip(string[] filePathList, string zipName)
{
MemoryStream ms = new MemoryStream();
byte[] buffer = null;
var context = HttpContext.Current;
using (ICSharpCode.SharpZipLib.Zip.ZipFile file = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ms))
{
file.BeginUpdate();
file.NameTransform = new MyNameTransfom();// , 。 , zip 。
foreach (var it in filePathList)
{
file.Add(context.Server.MapPath(it));
}
file.CommitUpdate();
buffer = new byte[ms.Length];
ms.Position = 0;
ms.Read(buffer, 0, buffer.Length);
}
context.Response.AddHeader("content-disposition", "attachment;filename=" + zipName);
context.Response.BinaryWrite(buffer);
context.Response.Flush();
context.Response.End();
}
/// <summary>
/// , files paths
/// </summary>
/// <param name="rootPath"> </param>
private void GetAllDirectories(string rootPath)
{
string[] subPaths = Directory.GetDirectories(rootPath);//
foreach (string path in subPaths)
{
GetAllDirectories(path);// : List
}
string[] files = Directory.GetFiles(rootPath);
foreach (string file in files)
{
this.files.Add(file);// List
}
if (subPaths.Length == files.Length && files.Length == 0)//
{
this.paths.Add(rootPath);//
}
}
/// <summary>
/// ( )
/// </summary>
/// <param name="zipfilepath"> </param>
/// <param name="unzippath"> </param>
/// <returns> </returns>
public List<string> UnZip(string zipfilepath, string unzippath)
{
//
List<string> unzipFiles = new List<string>();
// “\\”
if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false)
{
unzippath += "\\";
}
ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(unzippath);
string fileName = Path.GetFileName(theEntry.Name);
// 【 , 】
if (!string.IsNullOrEmpty(directoryName))
{
Directory.CreateDirectory(directoryName);
}
if (fileName != String.Empty)
{
// 0 ,
if (theEntry.CompressedSize == 0)
break;
//
directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);
//
Directory.CreateDirectory(directoryName);
//
unzipFiles.Add(unzippath + theEntry.Name);
FileStream streamWriter = File.Create(unzippath + theEntry.Name);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
GC.Collect();
return unzipFiles;
}
}
public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform
{
#region INameTransform
public string TransformDirectory(string name)
{
return null;
}
public string TransformFile(string name)
{
return Path.GetFileName(name);
}
#endregion
}
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
WebView2를 Visual Studio 2017 Express에서 사용할 수 있을 때까지Evergreen .Net Framework SDK 4.8 VisualStudio2017에서 NuGet을 사용하기 때문에 패키지 관리 방법을 packages.config 대신 PackageReference를 사용해야...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.