ZipOutputStream
chỉ nén tệp trong một thư mục. Tôi cũng muốn nén các thư mục con. Làm thế nào tôi có thể đạt được điều này?Zip thư mục con bằng cách sử dụng ZipOutputStream
Trả lời
Bạn phải theo dõi đệ quy thư mục của mình để thêm tất cả các tệp vào mã zip.
Xem helper này nhỏ nếu bạn muốn:
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO;
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
namespace Zip
{
/// <summary>
/// Uses Sharpziplib so as to create a non flat zip archive
/// </summary>
public abstract class ZipManager
{
/// <summary>
/// will zip directory .\toto as .\toto.zip
/// </summary>
/// <param name="stDirToZip"></param>
/// <returns></returns>
public static string CreateZip(string stDirToZip)
{
try
{
DirectoryInfo di = new DirectoryInfo(stDirToZip);
string stZipPath = di.Parent.FullName + "\\" + di.Name + ".zip";
CreateZip(stZipPath, stDirToZip);
return stZipPath;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Main method
/// </summary>
/// <param name="stZipPath">path of the archive wanted</param>
/// <param name="stDirToZip">path of the directory we want to create, without ending backslash</param>
public static void CreateZip(string stZipPath, string stDirToZip)
{
try
{
//Sanitize inputs
stDirToZip = Path.GetFullPath(stDirToZip);
stZipPath = Path.GetFullPath(stZipPath);
Console.WriteLine("Zip directory " + stDirToZip);
//Recursively parse the directory to zip
Stack<FileInfo> stackFiles = DirExplore(stDirToZip);
ZipOutputStream zipOutput = null;
if (File.Exists(stZipPath))
File.Delete(stZipPath);
Crc32 crc = new Crc32();
zipOutput = new ZipOutputStream(File.Create(stZipPath));
zipOutput.SetLevel(6); // 0 - store only to 9 - means best compression
Console.WriteLine(stackFiles.Count + " files to zip.\n");
int index = 0;
foreach (FileInfo fi in stackFiles)
{
++index;
int percent = (int)((float)index/((float)stackFiles.Count/100));
if (percent % 1 == 0)
{
Console.CursorLeft = 0;
Console.Write(_stSchon[index % _stSchon.Length].ToString() + " " + percent + "% done.");
}
FileStream fs = File.OpenRead(fi.FullName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
//Create the right arborescence within the archive
string stFileName = fi.FullName.Remove(0, stDirToZip.Length + 1);
ZipEntry entry = new ZipEntry(stFileName);
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 = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipOutput.PutNextEntry(entry);
zipOutput.Write(buffer, 0, buffer.Length);
}
zipOutput.Finish();
zipOutput.Close();
zipOutput = null;
}
catch (Exception)
{
throw;
}
}
static private Stack<FileInfo> DirExplore(string stSrcDirPath)
{
try
{
Stack<DirectoryInfo> stackDirs = new Stack<DirectoryInfo>();
Stack<FileInfo> stackPaths = new Stack<FileInfo>();
DirectoryInfo dd = new DirectoryInfo(Path.GetFullPath(stSrcDirPath));
stackDirs.Push(dd);
while (stackDirs.Count > 0)
{
DirectoryInfo currentDir = (DirectoryInfo)stackDirs.Pop();
try
{
//Process .\files
foreach (FileInfo fileInfo in currentDir.GetFiles())
{
stackPaths.Push(fileInfo);
}
//Process Subdirectories
foreach (DirectoryInfo diNext in currentDir.GetDirectories())
stackDirs.Push(diNext);
}
catch (Exception)
{//Might be a system directory
}
}
return stackPaths;
}
catch (Exception)
{
throw;
}
}
private static char[] _stSchon = new char[] { '-', '\\', '|', '/' };
}
}
Bài viết này bằng C# MVP Peter Bromberg có thể giải quyết vấn đề của bạn: Zip/Unzip folders and files with C#. Nó có mã hoàn chỉnh và một dự án mẫu.
Alternative (và tiện dụng hơn) giải pháp Tôi chỉ cần stumbled khi:
sử dụng dự án SevenZipSharp
var compressor = new SevenZipCompressor();
compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
compressor.CompressionLevel = CompressionLevel.High;
compressor.CompressionMode = CompressionMode.Create;
compressor.PreserveDirectoryRoot = false;
compressor.FastCompression = true;
compressor.CompressDirectory(dir.FullName, zipFile.FullName);
public static void ZipDirectoryKeepRelativeSubfolder(string zipFilePath, string directoryToZip)
{
var filenames = Directory.GetFiles(directoryToZip, "*.*", SearchOption.AllDirectories);
using (var s = new ZipOutputStream(File.Create(zipFilePath)))
{
s.SetLevel(9);// 0 - store only to 9 - means best compression
var buffer = new byte[4096];
foreach (var file in filenames)
{
var relativePath = file.Substring(directoryToZip.Length).TrimStart('\\');
var entry = new ZipEntry(relativePath);
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (var fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
s.Finish();
s.Close();
}
}
làm việc cho tôi, cảm ơn – mrbm
cách có kết thúc() và đóng() hoạt động, không phải với mẫu Vứt bỏ. :( –
- 1. Thư mục ZIP có thư mục con trong python
- 2. Nén thư mục chứa thư mục con
- 3. Cách giải nén thư mục zip bằng cách sử dụng mã php
- 4. Tạo lại cấu trúc thư mục bên trong tệp Zip bằng Java - Các thư mục trống
- 5. Tải xuống nhiều tệp dưới dạng thư mục zip bằng cách sử dụng php
- 6. Tạo tệp Zip bằng cách sử dụng SharpZipLib
- 7. Lệnh để nén thư mục bằng cách sử dụng thư mục cụ thể làm gốc
- 8. thư mục trong tệp zip khi sử dụng java.util.zip.ZipOutputStream
- 9. Java ZIP - cách giải nén thư mục?
- 10. Thư mục Zip đệ quy, lưu cho một thư mục con đã cho (Linux)
- 11. Cách đọc tên tệp đệ quy từ thư mục con bằng cách sử dụng LINQ
- 12. Di chuyển thư mục bằng cách sử dụng Qt
- 13. Liệt kê tất cả thư mục con và tệp trong thư mục bằng cách sử dụng php
- 14. Làm thế nào để tải xuống toàn bộ thư mục và thư mục con bằng cách sử dụng wget?
- 15. Tạo các thư mục con bên trong nhóm Amazon S3 bằng cách sử dụng tập lệnh
- 16. Lỗi khi tải tệp xuống thư mục con cục bộ bằng cách sử dụng WinSCP
- 17. Tạo thư mục con thông qua SQL INSERT bằng cách sử dụng FileTable
- 18. .htaccess cho trang web trong thư mục con bằng cách sử dụng khung công tác Yii
- 19. danh sách các lớp học theo thư mục/thư mục bằng cách sử dụng doxygen?
- 20. Cách ẩn thư mục bằng cách sử dụng java
- 21. Tạo thư mục bằng cách sử dụng tập tin bat
- 22. Thoát khỏi thư mục bằng cách sử dụng Git Bash
- 23. Mở thư mục bằng cách sử dụng C
- 24. Xóa thư mục trống bằng cách sử dụng msbuild
- 25. Zip toàn bộ thư mục trên S3
- 26. Sử dụng JQuery trong một thư mục con Khi MasterPage nằm trong thư mục gốc
- 27. Sử dụng thư mục con làm thư mục gốc với htaccess trong Apache 1.3
- 28. Sao chép tệp từ thư mục này sang thư mục khác bằng cách sử dụng vbscripting
- 29. Tạo tệp zip từ các thư mục
- 30. Sử dụng .htaccess để đặt thư mục con làm thư mục gốc
Tôi hy vọng bạn đã không bỏ câu hỏi này và sẽ trở lại để đánh dấu một câu trả lời hoặc ít nhất cho biết câu trả lời nào hữu ích. Trong số 200 câu hỏi của bạn, bạn sẽ có khoảng 120 câu trả lời cần được đánh dấu (nếu câu trả lời thỏa đáng), mỗi câu trả lời được đánh dấu sẽ giúp bạn có thêm 2 điểm đại diện và giúp người xem tương lai của câu hỏi của bạn biết câu trả lời hay nhất . 120 * 2rep = 240 đại diện bạn có thể đạt được. – slugster