מהו פורמט ZIP (קובץ ארכיון)
ZIP הוא פורמט קובץ ארכיון התומך בדחיסת נתונים ללא אובדן. קובץ ZIP עשוי להכיל קובץ אחד או יותר או תיקיות שדחוסו. קבצי ZIP משתמשים בדרך כלל בסיומות הקבצים .zip או .ZIP ובסוג המדיה MIME application/zip. ZIP משמש כפורמט קובץ בסיסי עבור תוכנות רבות, לרוב תחת שם שונה. כאשר נווטים במערכת קבצים דרך ממשק משתמש, סמל גרפי המייצג קובץ ZIP מופיע לעיתים קרובות כמסמך או אובייקט אחר עם סמל רוכסן בולט.
קיימות מספר דרכים לדחוס (לכווץ) קבצים
, תלוי במערכת ההפעלה שבה אתם משתמשים. ובכל יום כמעט אנו נדרשים לדחוס או לפתוח קבצים ולשלוח אותם לשרת אחסון או פלטפורמת שיתוף קבצים. למזלנו, ניתן לאוטומט את התהליך באמצעות Aspose.ZIP API
. הוא מאפשר לדחוס ולפרק קבצים מבלי לדאוג למבנה הקבצים הפנימי. מאמר זה מציג עבודה עם דחיסה של קובץ יחיד וכן של קבצים מרובים.
חבילת Aspose.ZIP ניתן להוסיף לפרויקט .NET שלכם באמצעות פקודת NuGet הבאה:
PM> Install-Package Aspose.Zip
איך לדחוס קובץ יחיד עם C#
- ראשית עלינו ליצור אובייקט של מחלקת FileStream class
עבור ארכיון ה‑ZIP הפלט.
- לטעון קובץ יחיד אל אובייקט ה‑FileStream
.
- ליצור אובייקט של מחלקת Archive class
.
- להוסיף את הקובץ לארכיון באמצעות השיטה Archive.CreateEntry
( “FileName”, FileStream ).
- ליצור את ארכיון ה‑ZIP באמצעות השיטה Archive.Save
(FileStream).
using (FileStream zipFile = File.Open(dataDir + "CompressSingleFile_out.zip", FileMode.Create))
{
//File to be added to archive
using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
{
using (var archive = new Archive(new ArchiveEntrySettings()))
{
archive.CreateEntry("alice29.txt", source1);
archive.Save(zipFile);
}
}
}
דחיסת קבצים מרובים עם C#
ההבדל בין דחיסת קובץ יחיד למספר קבצים הוא שעלינו לטעון קבצים נוספים אל ה‑FileStream ולהוסיף אותם כולם לארכיון ה‑ZIP באמצעות השיטה Archive.CreateEntry("FileName", FileStream). הקוד הבא מציג כיצד להוסיף מספר קבצים לארכיון ה‑ZIP באמצעות FileStream.
// Create FileStream for output ZIP archive
using (FileStream zipFile = File.Open("compressed_files.zip", FileMode.Create))
{
// File to be added to archive
using (FileStream source1 = File.Open("alice29.txt", FileMode.Open, FileAccess.Read))
{
// File to be added to archive
using (FileStream source2 = File.Open("asyoulike.txt", FileMode.Open, FileAccess.Read))
{
using (var archive = new Archive())
{
// Add files to the archive
archive.CreateEntry("alice29.txt", source1);
archive.CreateEntry("asyoulik3.txt", source2);
// ZIP the files
archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII, ArchiveComment = "two files are compressed in this archive" });
}
}
}
}
דחיסת קבצים באמצעות מחלקת FileInfo
קבצים ניתנים גם לטעינה באמצעות מחלקת FileInfo ולהוספה לארכיון ה‑ZIP באותו האופן כמו קודם. מחלקת FileInfo מספקת תכונות ושיטות למימוש יצירה, העתקה, מחיקה, העברה ופתיחה של קבצים, ותורמת ליצירת אובייקטים של FileStream.
using (FileStream zipFile = File.Open("compressed_files.zip", FileMode.Create))
{
// Files to be added to archive
FileInfo fi1 = new FileInfo("alice29.txt");
FileInfo fi2 = new FileInfo("fields.c");
using (var archive = new Archive())
{
// Add files to the archive
archive.CreateEntry("alice29.txt", fi1);
archive.CreateEntry("fields.c", fi2);
// Create ZIP archive
archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII });
}
}
אחסון קבצים בארכיונים ללא דחיסה
//Creates zip archive without compressing files
using (FileStream zipFile = File.Open(dataDir + "StoreMultipleFilesWithoutCompression_out.zip", FileMode.Create))
{
FileInfo fi1 = new FileInfo(dataDir + "alice29.txt");
FileInfo fi2 = new FileInfo(dataDir + "lcet10.txt");
using (Archive archive = new Archive(new ArchiveEntrySettings(new StoreCompressionSettings())))
{
archive.CreateEntry("alice29.txt", fi1);
archive.CreateEntry("lcet10.txt", fi2);
archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII });
}
}
איך לדחוס קבצים עם סיסמה ב‑C#
using (var archive = new Archive(new ArchiveEntrySettings(encryptionSettings: new TraditionalEncryptionSettings("pass"))))
{
archive.CreateEntry("entry_name1.dat", "input_file1.dat");
archive.CreateEntry("entry_name2.dat", "input_file2.dat");
archive.Save("result_archive.zip");
}
הפרמטר encryptionSettings משמש ליצירת ארכיון ZIP מוגן בסיסמה.
איך לפתוח קבצים עם סיסמה ב‑C#
using (var archive = new Archive("input_archive.zip", new ArchiveLoadOptions{DecryptionPassword = "pass"}))
{
archive.ExtractToDirectory("\\outputDirectory");
}
ה‑ArchiveLoadOptions עם ערך המאפיין DecryptionPassword משמש לפתיחת ארכיון ZIP מוגן בסיסמה.
לצפייה בדוגמאות מלאות וקבצי נתונים, אנא בקרו ב‑https://github.com/aspose-zip/Aspose.ZIP-for-.NET.
שימוש בדחיסת LZMA בתוך ארכיון ZIP
אלגוריתם Lempel–Ziv–Markov chain (LZMA) הוא אלגוריתם המשמש לביצוע דחיסת נתונים ללא אובדן. LZMA משתמש באלגוריתם דחיסת מילון, והזרם הדחוס הוא זרם של ביטים. דחיסת LZMA בתוך ארכיון ZIP מאפשרת למכולות ZIP להכיל ערכים דחוסים ב‑LZMA. הקוד הבא מציג יישום של דחיסת LZMA באמצעות Aspose.ZIP API
.
using (FileStream zipFile = File.Open(dataDir + "LZMACompression_out.zip", FileMode.Create))
{
using (Archive archive = new Archive(new ArchiveEntrySettings(new LzmaCompressionSettings())))
{
archive.CreateEntry("sample.txt", dataDir + "sample.txt");
archive.Save(zipFile);
}
}
שימוש בדחיסת BZip2 בתוך ארכיון ZIP
bzip2 הוא תוכנית חינמית וקוד פתוח לדחיסת קבצים המשתמשת באלגוריתם Burrows–Wheeler. היא דוחסת קבצים יחידים בלבד ואינה משמשת כמארז קבצים. היא פותחה על ידי Julian Seward ומתוחזקת על ידי Mark Wielaard ו‑Micah Snyder. הקוד הבא מציג יישום של דחיסת BZip2 באמצעות Aspose.ZIP API
.
using (FileStream zipFile = File.Open(dataDir + "Bzip2Compression_out.zip", FileMode.Create))
{
using (Archive archive = new Archive(new ArchiveEntrySettings(new Bzip2CompressionSettings())))
{
archive.CreateEntry("sample.txt", dataDir + "sample.txt");
archive.Save(zipFile);
}
}
שימוש בדחיסת PPMd בתוך ארכיון ZIP
Prediction by partial matching (PPM) היא טכניקת דחיסת נתונים סטטיסטית אדפטיבית המבוססת על מודלינג והצפנה של הקשר. מודלים של PPM משתמשים במערך של סמלים קודמים בזרם הסמלים הלא דחוס כדי לחזות את הסמל הבא בזרם. אלגוריתמים של PPM יכולים לשמש גם לקיבוץ נתונים לקבוצות חזויות בניתוח אשכולות. הקוד הבא מציג יישום של דחיסת PPMd באמצעות Aspose.ZIP API
.
using (FileStream zipFile = File.Open(dataDir + "PPMdCompression_out.zip", FileMode.Create))
{
using (Archive archive = new Archive(new ArchiveEntrySettings(new PPMdCompressionSettings())))
{
archive.CreateEntry("sample.txt", dataDir + "sample.txt");
archive.Save(zipFile);
}
}
פירוק ארכיון עם קובץ יחיד
using (FileStream fs = File.OpenRead(dataDir + "CompressSingleFile_out.zip"))
{
using (Archive archive = new Archive(fs))
{
int percentReady = 0;
archive.Entries[0].ExtractionProgressed += (s, e) =>
{
int percent = (int)((100 * e.ProceededBytes) / ((ArchiveEntry)s).UncompressedSize);
if (percent > percentReady)
{
Console.WriteLine(string.Format("{0}% decompressed", percent));
percentReady = percent;
}
};
archive.Entries[0].Extract(dataDir + "alice_extracted_out.txt");
}
}
פירוק ארכיון עם קבצים מרובים
using (FileStream zipFile = File.Open(dataDir + "CompressMultipleFiles_out.zip", FileMode.Open))
{
StringBuilder sb = new StringBuilder("Entries are: ");
int percentReady = 0;
using (Archive archive = new Archive(zipFile,
new ArchiveLoadOptions()
{
EntryListed = (s, e) => { sb.AppendFormat("{0}, ", e.Entry.Name); },
EntryExtractionProgressed = (s, e) =>
{
int percent = (int)((100 * e.ProceededBytes) / ((ArchiveEntry)s).UncompressedSize);
if (percent > percentReady)
{
Console.WriteLine(string.Format("{0}% compressed", percent)); percentReady = percent;
}
}
}))
{
Console.WriteLine(sb.ToString(0, sb.Length - 2));
using (var extracted = File.Create(dataDir + "alice_extracted_out.txt"))
{
using (var decompressed = archive.Entries[0].Open())
{
byte[] buffer = new byte[8192];
int bytesRead;
while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
{
extracted.Write(buffer, 0, bytesRead);
}
// Read from decompressed stream to extracting file.
}
}
percentReady = 0;
archive.Entries[1].Extract(dataDir + "asyoulik_extracted_out.txt");
}
}
חילוץ ארכיון מאוחסן ללא דחיסה
using (FileStream zipFile = File.Open(dataDir + "StoreMultipleFilesWithoutCompression_out.zip", FileMode.Open))
{
using (Archive archive = new Archive(zipFile))
{
using (var extracted = File.Create(dataDir + "alice_extracted_store_out.txt"))
{
using (var decompressed = archive.Entries[0].Open())
{
byte[] buffer = new byte[8192];
int bytesRead;
while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
{
extracted.Write(buffer, 0, bytesRead);
}
// Read from decompressed stream to extracting file.
}
}
using (var extracted = File.Create(dataDir + "asyoulik_extracted_store_out.txt"))
{
using (var decompressed = archive.Entries[1].Open())
{
byte[] buffer = new byte[8192];
int bytesRead;
while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
{
extracted.Write(buffer, 0, bytesRead);
}
// Read from decompressed stream to extracting file.
}
}
}
}
לדוגמאות מלאות וקבצי נתונים, אנא בקרו ב‑https://github.com/aspose-zip/Aspose.ZIP-for-.NET.