private void Zipup()
{
if (filesToZip.Count == 0)
{
System.Console.WriteLine("Nothing to do.");
return;
}
using (var raw = File.Open(_outputFileName, FileMode.Create, FileAccess.ReadWrite ))
{
using (var output= new ZipOutputStream(raw))
{
output.Password = "VerySecret!";
output.Encryption = EncryptionAlgorithm.WinZipAes256;
foreach (string inputFileName in filesToZip)
{
System.Console.WriteLine("file: {0}", inputFileName);
output.PutNextEntry(inputFileName);
using (var input = File.Open(inputFileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Write ))
{
byte[] buffer= new byte[2048];
int n;
while ((n= input.Read(buffer,0,buffer.Length)) > 0)
{
output.Write(buffer,0,n);
}
}
}
}
}
}
Private Sub Zipup()
Dim outputFileName As String = "XmlData.zip"
Dim filesToZip As String() = Directory.GetFiles(".", "*.xml")
If (filesToZip.Length = 0) Then
Console.WriteLine("Nothing to do.")
Else
Using raw As FileStream = File.Open(outputFileName, FileMode.Create, FileAccess.ReadWrite)
Using output As ZipOutputStream = New ZipOutputStream(raw)
output.Password = "VerySecret!"
output.Encryption = EncryptionAlgorithm.WinZipAes256
Dim inputFileName As String
For Each inputFileName In filesToZip
Console.WriteLine("file: {0}", inputFileName)
output.PutNextEntry(inputFileName)
Using input As FileStream = File.Open(inputFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim n As Integer
Dim buffer As Byte() = New Byte(2048) {}
Do While (n = input.Read(buffer, 0, buffer.Length) > 0)
output.Write(buffer, 0, n)
Loop
End Using
Next
End Using
End Using
End If
End Sub
private void Zipup()
{
if (filesToZip.Count == 0)
{
System.Console.WriteLine("Nothing to do.");
return;
}
using (var output= new ZipOutputStream(outputFileName))
{
output.Password = "VerySecret!";
output.Encryption = EncryptionAlgorithm.WinZipAes256;
foreach (string inputFileName in filesToZip)
{
System.Console.WriteLine("file: {0}", inputFileName);
output.PutNextEntry(inputFileName);
using (var input = File.Open(inputFileName, FileMode.Open, FileAccess.Read,
FileShare.Read | FileShare.Write ))
{
byte[] buffer= new byte[2048];
int n;
while ((n= input.Read(buffer,0,buffer.Length)) > 0)
{
output.Write(buffer,0,n);
}
}
}
}
}
Private Sub Zipup()
Dim outputFileName As String = "XmlData.zip"
Dim filesToZip As String() = Directory.GetFiles(".", "*.xml")
If (filesToZip.Length = 0) Then
Console.WriteLine("Nothing to do.")
Else
Using output As ZipOutputStream = New ZipOutputStream(outputFileName)
output.Password = "VerySecret!"
output.Encryption = EncryptionAlgorithm.WinZipAes256
Dim inputFileName As String
For Each inputFileName In filesToZip
Console.WriteLine("file: {0}", inputFileName)
output.PutNextEntry(inputFileName)
Using input As FileStream = File.Open(inputFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim n As Integer
Dim buffer As Byte() = New Byte(2048) {}
Do While (n = input.Read(buffer, 0, buffer.Length) > 0)
output.Write(buffer, 0, n)
Loop
End Using
Next
End Using
End If
End Sub
private void Zipup()
{
using (FileStream fs raw = File.Open(_outputFileName, FileMode.Create, FileAccess.ReadWrite ))
{
using (var output= new ZipOutputStream(fs))
{
output.Password = "VerySecret!";
output.Encryption = EncryptionAlgorithm.WinZipAes256;
output.PutNextEntry("entry1.txt");
byte[] buffer= System.Text.Encoding.ASCII.GetBytes("This is the content for entry #1.");
output.Write(buffer,0,buffer.Length);
output.PutNextEntry("entry2.txt"); // this will be zero length
output.PutNextEntry("entry3.txt");
buffer= System.Text.Encoding.ASCII.GetBytes("This is the content for entry #3.");
output.Write(buffer,0,buffer.Length);
}
}
}
private void Unzip()
{
byte[] buffer= new byte[2048];
int n;
using (var raw = File.Open(inputFileName, FileMode.Open, FileAccess.Read))
{
using (var input= new ZipInputStream(raw))
{
ZipEntry e;
while (( e = input.GetNextEntry()) != null)
{
if (e.IsDirectory) continue;
string outputPath = Path.Combine(extractDir, e.FileName);
using (var output = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
{
while ((n= input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer,0,n);
}
}
}
}
}
}
Private Sub UnZip()
Dim inputFileName As String = "MyArchive.zip"
Dim extractDir As String = "extract"
Dim buffer As Byte() = New Byte(2048) {}
Using raw As FileStream = File.Open(inputFileName, FileMode.Open, FileAccess.Read)
Using input As ZipInputStream = New ZipInputStream(raw)
Dim e As ZipEntry
Do While (Not e = input.GetNextEntry Is Nothing)
If Not e.IsDirectory Then
Using output As FileStream = File.Open(Path.Combine(extractDir, e.FileName), _
FileMode.Create, FileAccess.ReadWrite)
Dim n As Integer
Do While (n = input.Read(buffer, 0, buffer.Length) > 0)
output.Write(buffer, 0, n)
Loop
End Using
End If
Loop
End Using
End Using
End Sub
private void Unzip()
{
byte[] buffer= new byte[2048];
int n;
using (var input= new ZipInputStream(inputFileName))
{
ZipEntry e;
while (( e = input.GetNextEntry()) != null)
{
if (e.IsDirectory) continue;
string outputPath = Path.Combine(extractDir, e.FileName);
using (var output = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
{
while ((n= input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer,0,n);
}
}
}
}
}
Private Sub UnZip()
Dim inputFileName As String = "MyArchive.zip"
Dim extractDir As String = "extract"
Dim buffer As Byte() = New Byte(2048) {}
Using input As ZipInputStream = New ZipInputStream(inputFileName)
Dim e As ZipEntry
Do While (Not e = input.GetNextEntry Is Nothing)
If Not e.IsDirectory Then
Using output As FileStream = File.Open(Path.Combine(extractDir, e.FileName), _
FileMode.Create, FileAccess.ReadWrite)
Dim n As Integer
Do While (n = input.Read(buffer, 0, buffer.Length) > 0)
output.Write(buffer, 0, n)
Loop
End Using
End If
Loop
End Using
End Sub
byte[] buffer= new byte[2048];
int n;
using (var raw = File.Open(_inputFileName, FileMode.Open, FileAccess.Read ))
{
using (var input= new ZipInputStream(raw))
{
ZipEntry e;
while (( e = input.GetNextEntry()) != null)
{
input.Password = PasswordForEntry(e.FileName);
if (e.IsDirectory) continue;
string outputPath = Path.Combine(_extractDir, e.FileName);
using (var output = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
{
while ((n= input.Read(buffer,0,buffer.Length)) > 0)
{
output.Write(buffer,0,n);
}
}
}
}
}
var cipher = new ZipCrypto();
cipher.InitCipher(Password);
// Decrypt the header. This has a side effect of "further initializing the
// encryption keys" in the traditional zip encryption.
byte[] DecryptedMessage = cipher.DecryptMessage(EncryptedMessage);
Step 1 - Initializing the encryption keys
-----------------------------------------
Start with these keys:
Key(0) := 305419896 (0x12345678)
Key(1) := 591751049 (0x23456789)
Key(2) := 878082192 (0x34567890)
Then, initialize the keys with a password:
loop for i from 0 to length(password)-1
update_keys(password(i))
end loop
Where update_keys() is defined as:
update_keys(char):
Key(0) := crc32(key(0),char)
Key(1) := Key(1) + (Key(0) bitwiseAND 000000ffH)
Key(1) := Key(1) * 134775813 + 1
Key(2) := crc32(key(2),key(1) rightshift 24)
end update_keys
Where crc32(old_crc,char) is a routine that given a CRC value and a
character, returns an updated CRC value after applying the CRC-32
algorithm described elsewhere in this document.
private void WriteEntry (String filename, Stream output)
{
DataSet ds1 = ObtainDataSet();
ds1.WriteXml(output);
}
private void Run()
{
using (var zip = new ZipFile())
{
zip.AddEntry(zipEntryName, WriteEntry);
zip.Save(zipFileName);
}
}
Private Sub WriteEntry (ByVal filename As String, ByVal output As Stream)
DataSet ds1 = ObtainDataSet()
ds1.WriteXml(stream)
End Sub
Public Sub Run()
Using zip = New ZipFile
zip.AddEntry(zipEntryName, New WriteDelegate(AddressOf WriteEntry))
zip.Save(zipFileName)
End Using
End Sub
using (ZipFile zip = ZipFile.Read("PackedDocuments.zip"))
{
foreach (string s1 in zip.EntryFilenames)
{
if (s1.EndsWith(".txt"))
{
zip[s1].Extract("textfiles");
}
}
}
Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip")
Dim s1 As String
For Each s1 In zip.EntryFilenames
If s1.EndsWith(".txt") Then
zip(s1).Extract("textfiles")
End If
Next
End Using
String sZipPath = "Airborne.zip";
String sFilePath = "Readme.txt";
String sRootFolder = "Digado";
using (ZipFile zip = ZipFile.Read(sZipPath))
{
if (zip.EntryFileNames.Contains(sFilePath))
{
// use the string indexer on the zip file
zip[sFileName].Extract(sRootFolder,
ExtractExistingFileAction.OverwriteSilently);
}
}
Dim sZipPath as String = "Airborne.zip"
Dim sFilePath As String = "Readme.txt"
Dim sRootFolder As String = "Digado"
Using zip As ZipFile = ZipFile.Read(sZipPath)
If zip.EntryFileNames.Contains(sFilePath)
' use the string indexer on the zip file
zip(sFilePath).Extract(sRootFolder, _
ExtractExistingFileAction.OverwriteSilently)
End If
End Using
using (var zip = ZipFile.Read(FilePath))
{
foreach (ZipEntry e in zip)
{
if (e.UsesEncryption)
e.ExtractWithPassword("Secret!");
else
e.Extract();
}
}
Using zip As ZipFile = ZipFile.Read(FilePath)
Dim e As ZipEntry
For Each e In zip
If (e.UsesEncryption)
e.ExtractWithPassword("Secret!")
Else
e.Extract
End If
Next
End Using
using (ZipFile zip = new ZipFile(ZipFileToRead))
{
ZipEntry e1= zip["Elevation.mp3"];
using (Ionic.Zlib.CrcCalculatorStream s = e1.OpenReader())
{
byte[] buffer = new byte[4096];
int n, totalBytesRead= 0;
do {
n = s.Read(buffer,0, buffer.Length);
totalBytesRead+=n;
} while (n>0);
if (s.Crc32 != e1.Crc32)
throw new Exception(string.Format("The Zip Entry failed the CRC Check. (0x{0:X8}!=0x{1:X8})", s.Crc32, e1.Crc32));
if (totalBytesRead != e1.UncompressedSize)
throw new Exception(string.Format("We read an unexpected number of bytes. ({0}!={1})", totalBytesRead, e1.UncompressedSize));
}
}
Using zip As New ZipFile(ZipFileToRead)
Dim e1 As ZipEntry = zip.Item("Elevation.mp3")
Using s As Ionic.Zlib.CrcCalculatorStream = e1.OpenReader
Dim n As Integer
Dim buffer As Byte() = New Byte(4096) {}
Dim totalBytesRead As Integer = 0
Do
n = s.Read(buffer, 0, buffer.Length)
totalBytesRead = (totalBytesRead + n)
Loop While (n > 0)
If (s.Crc32 <> e1.Crc32) Then
Throw New Exception(String.Format("The Zip Entry failed the CRC Check. (0x{0:X8}!=0x{1:X8})", s.Crc32, e1.Crc32))
End If
If (totalBytesRead <> e1.UncompressedSize) Then
Throw New Exception(String.Format("We read an unexpected number of bytes. ({0}!={1})", totalBytesRead, e1.UncompressedSize))
End If
End Using
End Using
using (ZipFile zip = new ZipFile(ZipFileToCreate))
{
ZipEntry e1= zip.AddFile(@"notes\Readme.txt");
ZipEntry e2= zip.AddFile(@"music\StopThisTrain.mp3");
e2.CompressionMethod = CompressionMethod.None;
zip.Save();
}
Using zip As New ZipFile(ZipFileToCreate)
zip.AddFile("notes\Readme.txt")
Dim e2 as ZipEntry = zip.AddFile("music\StopThisTrain.mp3")
e2.CompressionMethod = CompressionMethod.None
zip.Save
End Using
// Create a zip archive with AES Encryption.
using (ZipFile zip = new ZipFile())
{
zip.AddFile("ReadMe.txt")
ZipEntry e1= zip.AddFile("2008-Regional-Sales-Report.pdf");
e1.Encryption= EncryptionAlgorithm.WinZipAes256;
e1.Password= "Top.Secret.No.Peeking!";
zip.Save("EncryptedArchive.zip");
}
// Extract a zip archive that uses AES Encryption.
// You do not need to specify the algorithm during extraction.
using (ZipFile zip = ZipFile.Read("EncryptedArchive.zip"))
{
// Specify the password that is used during extraction, for
// all entries that require a password:
zip.Password= "Top.Secret.No.Peeking!";
zip.ExtractAll("extractDirectory");
}
' Create a zip that uses Encryption.
Using zip As New ZipFile()
zip.AddFile("ReadMe.txt")
Dim e1 as ZipEntry
e1= zip.AddFile("2008-Regional-Sales-Report.pdf")
e1.Encryption= EncryptionAlgorithm.WinZipAes256
e1.Password= "Top.Secret.No.Peeking!"
zip.Save("EncryptedArchive.zip")
End Using
' Extract a zip archive that uses AES Encryption.
' You do not need to specify the algorithm during extraction.
Using (zip as ZipFile = ZipFile.Read("EncryptedArchive.zip"))
' Specify the password that is used during extraction, for
' all entries that require a password:
zip.Password= "Top.Secret.No.Peeking!"
zip.ExtractAll("extractDirectory")
End Using
// create a file with encryption
using (ZipFile zip = new ZipFile())
{
ZipEntry entry;
entry= zip.AddFile("Declaration.txt");
entry.Password= "123456!";
entry = zip.AddFile("Report.xls");
entry.Password= "1Secret!";
zip.Save("EncryptedArchive.zip");
}
// extract entries that use encryption
using (ZipFile zip = ZipFile.Read("EncryptedArchive.zip"))
{
ZipEntry entry;
entry = zip["Declaration.txt"];
entry.Password = "123456!";
entry.Extract("extractDir");
entry = zip["Report.xls"];
entry.Password = "1Secret!";
entry.Extract("extractDir");
}
Using zip As New ZipFile
Dim entry as ZipEntry
entry= zip.AddFile("Declaration.txt")
entry.Password= "123456!"
entry = zip.AddFile("Report.xls")
entry.Password= "1Secret!"
zip.Save("EncryptedArchive.zip")
End Using
' extract entries that use encryption
Using (zip as ZipFile = ZipFile.Read("EncryptedArchive.zip"))
Dim entry as ZipEntry
entry = zip("Declaration.txt")
entry.Password = "123456!"
entry.Extract("extractDir")
entry = zip("Report.xls")
entry.Password = "1Secret!"
entry.Extract("extractDir")
End Using
public static void ExtractProgress(object sender, ExtractProgressEventArgs e)
{
if (e.EventType == ZipProgressEventType.Extracting_BeforeExtractEntry)
Console.WriteLine("extract {0} ", e.CurrentEntry.FileName);
else if (e.EventType == ZipProgressEventType.Extracting_ExtractEntryWouldOverwrite)
{
ZipEntry entry = e.CurrentEntry;
string response = null;
// Ask the user if he wants overwrite the file
do
{
Console.Write("Overwrite {0} in {1} ? (y/n/C) ", entry.FileName, e.ExtractLocation);
response = Console.ReadLine();
Console.WriteLine();
} while (response != null && response[0]!='Y' &&
response[0]!='N' && response[0]!='C');
if (response[0]=='C')
e.Cancel = true;
else if (response[0]=='Y')
entry.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
else
entry.ExtractExistingFile= ExtractExistingFileAction.DoNotOverwrite;
}
}
using (var zip = new ZipFile())
{
zip.AlternateEnoding = System.Text.Encoding.GetEncoding("ibm861");
zip.AlternateEnodingUsage = ZipOption.Always;
zip.AddFileS(arrayOfFiles);
zip.Save("Myarchive-Encoded-in-IBM861.zip");
}
using (var zip = new ZipFile())
{
var e = zip.UpdateFile("Descriptions.mme", "");
e.IsText = true;
zip.Save(zipPath);
}
Using zip As New ZipFile
Dim e2 as ZipEntry = zip.AddFile("Descriptions.mme", "")
e.IsText= True
zip.Save(zipPath)
End Using
String[] itemnames= {
"c:\\fixedContent\\Readme.txt",
"MyProposal.docx",
"c:\\SupportFiles", // a directory
"images\\Image1.jpg"
};
try
{
using (ZipFile zip = new ZipFile())
{
for (int i = 1; i < itemnames.Length; i++)
{
// will add Files or Dirs, recurses and flattens subdirectories
zip.AddItem(itemnames[i],"flat");
}
zip.Save(ZipToCreate);
}
}
catch (System.Exception ex1)
{
System.Console.Error.WriteLine("exception: {0}", ex1);
}
Dim itemnames As String() = _
New String() { "c:\fixedContent\Readme.txt", _
"MyProposal.docx", _
"SupportFiles", _
"images\Image1.jpg" }
Try
Using zip As New ZipFile
Dim i As Integer
For i = 1 To itemnames.Length - 1
' will add Files or Dirs, recursing and flattening subdirectories.
zip.AddItem(itemnames(i), "flat")
Next i
zip.Save(ZipToCreate)
End Using
Catch ex1 As Exception
Console.Error.WriteLine("exception: {0}", ex1.ToString())
End Try
try
{
using (ZipFile zip = new ZipFile())
{
zip.AddFile("c:\\photos\\personal\\7440-N49th.png");
zip.AddFile("c:\\Desktop\\2008-Regional-Sales-Report.pdf");
zip.AddFile("ReadMe.txt");
zip.Save("Package.zip");
}
}
catch (System.Exception ex1)
{
System.Console.Error.WriteLine("exception: " + ex1);
}
Try
Using zip As ZipFile = New ZipFile
zip.AddFile("c:\photos\personal\7440-N49th.png")
zip.AddFile("c:\Desktop\2008-Regional-Sales-Report.pdf")
zip.AddFile("ReadMe.txt")
zip.Save("Package.zip")
End Using
Catch ex1 As Exception
Console.Error.WriteLine("exception: {0}", ex1.ToString)
End Try
try
{
using (ZipFile zip = new ZipFile())
{
// the following entry will be inserted at the root in the archive.
zip.AddFile("c:\\datafiles\\ReadMe.txt", "");
// this image file will be inserted into the "images" directory in the archive.
zip.AddFile("c:\\photos\\personal\\7440-N49th.png", "images");
// the following will result in a password-protected file called
// files\\docs\\2008-Regional-Sales-Report.pdf in the archive.
zip.Password = "EncryptMe!";
zip.AddFile("c:\\Desktop\\2008-Regional-Sales-Report.pdf", "files\\docs");
zip.Save("Archive.zip");
}
}
catch (System.Exception ex1)
{
System.Console.Error.WriteLine("exception: {0}", ex1);
}
Try
Using zip As ZipFile = New ZipFile
' the following entry will be inserted at the root in the archive.
zip.AddFile("c:\datafiles\ReadMe.txt", "")
' this image file will be inserted into the "images" directory in the archive.
zip.AddFile("c:\photos\personal\7440-N49th.png", "images")
' the following will result in a password-protected file called
' files\\docs\\2008-Regional-Sales-Report.pdf in the archive.
zip.Password = "EncryptMe!"
zip.AddFile("c:\Desktop\2008-Regional-Sales-Report.pdf", "files\documents")
zip.Save("Archive.zip")
End Using
Catch ex1 As Exception
Console.Error.WriteLine("exception: {0}", ex1)
End Try
String ZipFileToCreate = "archive1.zip";
String DirectoryToZip = "c:\\reports";
using (ZipFile zip = new ZipFile())
{
// Store all files found in the top level directory, into the zip archive.
String[] filenames = System.IO.Directory.GetFiles(DirectoryToZip);
zip.AddFiles(filenames);
zip.Save(ZipFileToCreate);
}
Dim ZipFileToCreate As String = "archive1.zip"
Dim DirectoryToZip As String = "c:\reports"
Using zip As ZipFile = New ZipFile
' Store all files found in the top level directory, into the zip archive.
Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
zip.AddFiles(filenames)
zip.Save(ZipFileToCreate)
End Using
using (ZipFile zip1 = new ZipFile())
{
// UpdateFile might more accurately be called "AddOrUpdateFile"
zip1.UpdateFile("MyDocuments\\Readme.txt");
zip1.UpdateFile("CustomerList.csv");
zip1.Comment = "This zip archive has been created.";
zip1.Save("Content.zip");
}
using (ZipFile zip2 = ZipFile.Read("Content.zip"))
{
zip2.UpdateFile("Updates\\Readme.txt");
zip2.Comment = "This zip archive has been updated: The Readme.txt file has been changed.";
zip2.Save();
}
Using zip1 As New ZipFile
' UpdateFile might more accurately be called "AddOrUpdateFile"
zip1.UpdateFile("MyDocuments\Readme.txt")
zip1.UpdateFile("CustomerList.csv")
zip1.Comment = "This zip archive has been created."
zip1.Save("Content.zip")
End Using
Using zip2 As ZipFile = ZipFile.Read("Content.zip")
zip2.UpdateFile("Updates\Readme.txt")
zip2.Comment = "This zip archive has been updated: The Readme.txt file has been changed."
zip2.Save
End Using
string Content = "This string will be the content of the Readme.txt file in the zip archive.";
using (ZipFile zip1 = new ZipFile())
{
zip1.AddFile("MyDocuments\\Resume.doc", "files");
zip1.AddEntry("Readme.txt", Content);
zip1.Comment = "This zip file was created at " + System.DateTime.Now.ToString("G");
zip1.Save("Content.zip");
}
Public Sub Run()
Dim Content As String = "This string will be the content of the Readme.txt file in the zip archive."
Using zip1 As ZipFile = New ZipFile
zip1.AddEntry("Readme.txt", Content)
zip1.AddFile("MyDocuments\Resume.doc", "files")
zip1.Comment = ("This zip file was created at " & DateTime.Now.ToString("G"))
zip1.Save("Content.zip")
End Using
End Sub
String zipToCreate = "Content.zip";
String fileNameInArchive = "Content-From-Stream.bin";
using (System.IO.Stream streamToRead = MyStreamOpener())
{
using (ZipFile zip = new ZipFile())
{
ZipEntry entry= zip.AddEntry(fileNameInArchive, streamToRead);
zip.AddFile("Readme.txt");
zip.Save(zipToCreate); // the stream is read implicitly here
}
}
Dim zipToCreate As String = "Content.zip"
Dim fileNameInArchive As String = "Content-From-Stream.bin"
Using streamToRead as System.IO.Stream = MyStreamOpener()
Using zip As ZipFile = New ZipFile()
Dim entry as ZipEntry = zip.AddEntry(fileNameInArchive, streamToRead)
zip.AddFile("Readme.txt")
zip.Save(zipToCreate) '' the stream is read implicitly, here
End Using
End Using
var c1= new System.Data.SqlClient.SqlConnection(connstring1);
var da = new System.Data.SqlClient.SqlDataAdapter()
{
SelectCommand= new System.Data.SqlClient.SqlCommand(strSelect, c1)
};
DataSet ds1 = new DataSet();
da.Fill(ds1, "Invoices");
using(Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
{
zip.AddEntry(zipEntryName, (name,stream) => ds1.WriteXml(stream) );
zip.Save(zipFileName);
}
using (var input = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ))
{
using(Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
{
zip.AddEntry(zipEntryName, (name,output) =>
{
byte[] buffer = new byte[BufferSize];
int n;
while ((n = input.Read(buffer, 0, buffer.Length)) != 0)
{
// could transform the data here...
output.Write(buffer, 0, n);
// could update a progress bar here
}
});
zip.Save(zipFileName);
}
}
Private Sub WriteEntry (ByVal name As String, ByVal output As Stream)
Using input As FileStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim n As Integer = -1
Dim buffer As Byte() = New Byte(BufferSize){}
Do While n <> 0
n = input.Read(buffer, 0, buffer.Length)
output.Write(buffer, 0, n)
Loop
End Using
End Sub
Public Sub Run()
Using zip = New ZipFile
zip.AddEntry(zipEntryName, New WriteDelegate(AddressOf WriteEntry))
zip.Save(zipFileName)
End Using
End Sub
using(Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
{
zip.AddEntry(zipEntryName,
(name) => File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ),
(name, stream) => stream.Close()
);
zip.Save(zipFileName);
}
Function MyStreamOpener(ByVal entryName As String) As Stream
'' This simply opens a file. You probably want to do somethinig
'' more involved here: open a stream to read from a database,
'' open a stream on an HTTP connection, and so on.
Return File.OpenRead(entryName)
End Function
Sub MyStreamCloser(entryName As String, stream As Stream)
stream.Close()
End Sub
Public Sub Run()
Dim dirToZip As String = "fodder"
Dim zipFileToCreate As String = "Archive.zip"
Dim opener As OpenDelegate = AddressOf MyStreamOpener
Dim closer As CloseDelegate = AddressOf MyStreamCloser
Dim numFilestoAdd As Int32 = 4
Using zip As ZipFile = New ZipFile
Dim i As Integer
For i = 0 To numFilesToAdd - 1
zip.AddEntry(String.Format("content-{0:000}.txt"), opener, closer)
Next i
zip.Save(zipFileToCreate)
End Using
End Sub
public void ZipUp(string targetZip, string directory)
{
using (var zip = new ZipFile())
{
zip.AddDirectory(directory, System.IO.Path.GetFileName(directory));
zip.Save(targetZip);
}
}
String ZipFileToCreate = "archive1.zip";
String DirectoryToZip = "c:\\reports";
using (ZipFile zip = new ZipFile())
{
// Store all files found in the top level directory, into the zip archive.
String[] filenames = System.IO.Directory.GetFiles(DirectoryToZip);
zip.AddFiles(filenames, "files");
zip.Save(ZipFileToCreate);
}
Dim ZipFileToCreate As String = "archive1.zip"
Dim DirectoryToZip As String = "c:\reports"
Using zip As ZipFile = New ZipFile()
Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
zip.AddFiles(filenames, "files")
zip.Save(ZipFileToCreate)
End Using
using (ZipFile zip = new ZipFile())
{
// Store all files found in the top level directory, into the zip archive.
// note: this code does not recurse subdirectories!
String[] filenames = System.IO.Directory.GetFiles(DirectoryToZip);
zip.AddFiles(filenames, "files");
zip.Save("Backup.zip");
}
Using zip As New ZipFile
' Store all files found in the top level directory, into the zip archive.
' note: this code does not recurse subdirectories!
Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
zip.AddFiles(filenames, "files")
zip.Save("Backup.zip")
End Using
using (ZipFile zip = new ZipFile("Backup.zip", Console.Out))
{
// Store all files found in the top level directory, into the zip archive.
// note: this code does not recurse subdirectories!
// Status messages will be written to Console.Out
String[] filenames = System.IO.Directory.GetFiles(DirectoryToZip);
zip.AddFiles(filenames);
zip.Save();
}
Using zip As New ZipFile("Backup.zip", Console.Out)
' Store all files found in the top level directory, into the zip archive.
' note: this code does not recurse subdirectories!
' Status messages will be written to Console.Out
Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
zip.AddFiles(filenames)
zip.Save()
End Using
String ZipFileToRead = "ArchiveToModify.zip";
System.DateTime Threshold = new System.DateTime(2007,12,31);
using (ZipFile zip = ZipFile.Read(ZipFileToRead))
{
var EntriesToRemove = new System.Collections.Generic.List<ZipEntry>();
foreach (ZipEntry e in zip)
{
if (e.LastModified < Threshold)
{
// We cannot remove the entry from the list, within the context of
// an enumeration of said list.
// So we add the doomed entry to a list to be removed later.
EntriesToRemove.Add(e);
}
}
// actually remove the doomed entries.
foreach (ZipEntry zombie in EntriesToRemove)
zip.RemoveEntry(zombie);
zip.Comment= String.Format("This zip archive was updated at {0}.",
System.DateTime.Now.ToString("G"));
// save with a different name
zip.Save("Archive-Updated.zip");
}
Dim ZipFileToRead As String = "ArchiveToModify.zip"
Dim Threshold As New DateTime(2007, 12, 31)
Using zip As ZipFile = ZipFile.Read(ZipFileToRead)
Dim EntriesToRemove As New System.Collections.Generic.List(Of ZipEntry)
Dim e As ZipEntry
For Each e In zip
If (e.LastModified < Threshold) Then
' We cannot remove the entry from the list, within the context of
' an enumeration of said list.
' So we add the doomed entry to a list to be removed later.
EntriesToRemove.Add(e)
End If
Next
' actually remove the doomed entries.
Dim zombie As ZipEntry
For Each zombie In EntriesToRemove
zip.RemoveEntry(zombie)
Next
zip.Comment = String.Format("This zip archive was updated at {0}.", DateTime.Now.ToString("G"))
'save as a different name
zip.Save("Archive-Updated.zip")
End Using
String zipFileToRead= "PackedDocuments.zip";
string candidate = "DatedMaterial.xps";
using (ZipFile zip = ZipFile.Read(zipFileToRead))
{
if (zip.EntryFilenames.Contains(candidate))
{
zip.RemoveEntry(candidate);
zip.Comment= String.Format("The file '{0}' has been removed from this archive.",
Candidate);
zip.Save();
}
}
Dim zipFileToRead As String = "PackedDocuments.zip"
Dim candidate As String = "DatedMaterial.xps"
Using zip As ZipFile = ZipFile.Read(zipFileToRead)
If zip.EntryFilenames.Contains(candidate) Then
zip.RemoveEntry(candidate)
zip.Comment = String.Format("The file '{0}' has been removed from this archive.", Candidate)
zip.Save
End If
End Using
using (ZipFile zip = ZipFile.Read(zipfile))
{
foreach (ZipEntry e in zip)
{
if (WantThisEntry(e.FileName))
zip.Extract(e.FileName, Console.OpenStandardOutput());
}
} // Dispose() is called implicitly here.
Using zip As ZipFile = ZipFile.Read(zipfile)
Dim e As ZipEntry
For Each e In zip
If WantThisEntry(e.FileName) Then
zip.Extract(e.FileName, Console.OpenStandardOutput())
End If
Next
End Using ' Dispose is implicity called here
String TargetDirectory= "unpack";
using(ZipFile zip= ZipFile.Read(ZipFileToExtract))
{
zip.ExtractExistingFile= ExtractExistingFileAction.OverwriteSilently;
zip.ExtractAll(TargetDirectory);
}
Dim TargetDirectory As String = "unpack"
Using zip As ZipFile = ZipFile.Read(ZipFileToExtract)
zip.ExtractExistingFile= ExtractExistingFileAction.OverwriteSilently
zip.ExtractAll(TargetDirectory)
End Using
String TargetDirectory= "c:\\unpack";
using(ZipFile zip= ZipFile.Read(ZipFileToExtract))
{
zip.ExtractAll(TargetDirectory, ExtractExistingFileAction.DontOverwrite);
}
Dim TargetDirectory As String = "c:\unpack"
Using zip As ZipFile = ZipFile.Read(ZipFileToExtract)
zip.ExtractAll(TargetDirectory, ExtractExistingFileAction.DontOverwrite)
End Using
string zipToExtract = "MyArchive.zip";
string extractDirectory = "extract";
var options = new ReadOptions
{
StatusMessageWriter = System.Console.Out,
Encoding = System.Text.Encoding.GetEncoding(950)
};
using (ZipFile zip = ZipFile.Read(zipToExtract, options))
{
foreach (ZipEntry e in zip)
{
e.Extract(extractDirectory);
}
}
Dim zipToExtract as String = "MyArchive.zip"
Dim extractDirectory as String = "extract"
Dim options as New ReadOptions
options.Encoding = System.Text.Encoding.GetEncoding(950)
options.StatusMessageWriter = System.Console.Out
Using zip As ZipFile = ZipFile.Read(zipToExtract, options)
Dim e As ZipEntry
For Each e In zip
e.Extract(extractDirectory)
Next
End Using
var options = new ReadOptions
{
StatusMessageWriter = new System.IO.StringWriter()
};
using (ZipFile zip = ZipFile.Read("PackedDocuments.zip", options))
{
var Threshold = new DateTime(2007,7,4);
// We cannot remove the entry from the list, within the context of
// an enumeration of said list.
// So we add the doomed entry to a list to be removed later.
// pass 1: mark the entries for removal
var MarkedEntries = new System.Collections.Generic.List<ZipEntry>();
foreach (ZipEntry e in zip)
{
if (e.LastModified < Threshold)
MarkedEntries.Add(e);
}
// pass 2: actually remove the entry.
foreach (ZipEntry zombie in MarkedEntries)
zip.RemoveEntry(zombie);
zip.Comment = "This archive has been updated.";
zip.Save();
}
// can now use contents of sw, eg store in an audit log
Dim options as New ReadOptions
options.StatusMessageWriter = New System.IO.StringWriter
Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip", options)
Dim Threshold As New DateTime(2007, 7, 4)
' We cannot remove the entry from the list, within the context of
' an enumeration of said list.
' So we add the doomed entry to a list to be removed later.
' pass 1: mark the entries for removal
Dim MarkedEntries As New System.Collections.Generic.List(Of ZipEntry)
Dim e As ZipEntry
For Each e In zip
If (e.LastModified < Threshold) Then
MarkedEntries.Add(e)
End If
Next
' pass 2: actually remove the entry.
Dim zombie As ZipEntry
For Each zombie In MarkedEntries
zip.RemoveEntry(zombie)
Next
zip.Comment = "This archive has been updated."
zip.Save
End Using
' can now use contents of sw, eg store in an audit log
using (ZipFile zip = ZipFile.Read(InputStream))
{
zip.Extract("NameOfEntryInArchive.doc", OutputStream);
}
Using zip as ZipFile = ZipFile.Read(InputStream)
zip.Extract("NameOfEntryInArchive.doc", OutputStream)
End Using
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(@"c:\reports\January");
zip.Save("January.zip");
}
Using zip As New ZipFile()
zip.AddDirectory("c:\reports\January")
zip.Save("January.zip")
End Using
using (ZipFile zip = ZipFile.Read("ExistingArchive.zip"))
{
zip.AddFile("NewData.csv");
zip.Save("UpdatedArchive.zip");
}
Using zip As ZipFile = ZipFile.Read("ExistingArchive.zip")
zip.AddFile("NewData.csv")
zip.Save("UpdatedArchive.zip")
End Using
using (var zip = new Ionic.Zip.ZipFile())
{
zip.CompressionLevel= Ionic.Zlib.CompressionLevel.BestCompression;
zip.Password = "VerySecret.";
zip.Encryption = EncryptionAlgorithm.WinZipAes128;
zip.AddFile(sourceFileName);
MemoryStream output = new MemoryStream();
zip.Save(output);
byte[] zipbytes = output.ToArray();
}
using (var fs = new FileSteeam(filename, FileMode.Open))
{
using (var zip = Ionic.Zip.ZipFile.Read(inputStream))
{
zip.AddEntry("Name1.txt", "this is the content");
zip.Save(inputStream); // NO NO NO!!
}
}
using (var zip = Ionic.Zip.ZipFile.Read(filename))
{
zip.AddEntry("Name1.txt", "this is the content");
zip.Save(); // YES!
}
using (ZipFile zip = new ZipFile())
{
// To just match on filename wildcards,
// use the shorthand form of the selectionCriteria string.
zip.AddSelectedFiles("*.csv");
zip.Save(PathToZipArchive);
}
Using zip As ZipFile = New ZipFile()
zip.AddSelectedFiles("*.csv")
zip.Save(PathToZipArchive)
End Using
using (ZipFile zip = new ZipFile())
{
// Use a compound expression in the selectionCriteria string.
zip.AddSelectedFiles("name = *.xml and size > 1024kb", true);
zip.Save(PathToZipArchive);
}
Using zip As ZipFile = New ZipFile()
' Use a compound expression in the selectionCriteria string.
zip.AddSelectedFiles("name = *.xml and size > 1024kb", true)
zip.Save(PathToZipArchive)
End Using
using (ZipFile zip = new ZipFile())
{
// Use a compound expression in the selectionCriteria string.
zip.AddSelectedFiles("name = *.xml and size > 1024kb", "d:\\rawdata");
zip.Save(PathToZipArchive);
}
Using zip As ZipFile = New ZipFile()
' Use a compound expression in the selectionCriteria string.
zip.AddSelectedFiles("name = *.xml and size > 1024kb", "d:\rawdata)
zip.Save(PathToZipArchive)
End Using
using (ZipFile zip = new ZipFile())
{
// Use a compound expression in the selectionCriteria string.
zip.AddSelectedFiles("name = *.csv and mtime > 2009-02-14", "files", true);
zip.Save(PathToZipArchive);
}
Using zip As ZipFile = New ZipFile()
' Use a compound expression in the selectionCriteria string.
zip.AddSelectedFiles("name = *.csv and mtime > 2009-02-14", "files", true)
zip.Save(PathToZipArchive)
End Using
Using Zip As ZipFile = New ZipFile(zipfile)
Zip.AddSelectedFfiles("name != 'excludethis\*.*'", datapath, True)
Zip.Save()
End Using
using (ZipFile zip = new ZipFile())
{
// Use a compound expression in the selectionCriteria string.
zip.AddSelectedFiles("name = *.psd and mtime > 2009-02-14", "photos", "content");
zip.Save(PathToZipArchive);
}
Using zip As ZipFile = New ZipFile
zip.AddSelectedFiles("name = *.psd and mtime > 2009-02-14", "photos", "content")
zip.Save(PathToZipArchive)
End Using
using (ZipFile zip = new ZipFile())
{
zip.AddSelectedFiles("name != *.pst", SourceDirectory, "backup", true);
zip.Save(PathToZipArchive);
}
Using zip As ZipFile = New ZipFile
zip.AddSelectedFiles("name != *.pst", SourceDirectory, "backup", true)
zip.Save(PathToZipArchive)
End Using
using (ZipFile zip1 = ZipFile.Read(ZipFileName))
{
var PhotoShopFiles = zip1.SelectEntries("*.psd");
foreach (ZipEntry psd in PhotoShopFiles)
{
psd.Extract();
}
}
Using zip1 As ZipFile = ZipFile.Read(ZipFileName)
Dim PhotoShopFiles as ICollection(Of ZipEntry)
PhotoShopFiles = zip1.SelectEntries("*.psd")
Dim psd As ZipEntry
For Each psd In PhotoShopFiles
psd.Extract
Next
End Using
using (ZipFile zip1 = ZipFile.Read(ZipFileName))
{
var UpdatedPhotoShopFiles = zip1.SelectEntries("*.psd", "UpdatedFiles");
foreach (ZipEntry e in UpdatedPhotoShopFiles)
{
// prompt for extract here
if (WantExtract(e.FileName))
e.Extract();
}
}
Using zip1 As ZipFile = ZipFile.Read(ZipFileName)
Dim UpdatedPhotoShopFiles As ICollection(Of ZipEntry) = zip1.SelectEntries("*.psd", "UpdatedFiles")
Dim e As ZipEntry
For Each e In UpdatedPhotoShopFiles
' prompt for extract here
If Me.WantExtract(e.FileName) Then
e.Extract
End If
Next
End Using
using (ZipFile zip1 = ZipFile.Read(ZipFileName))
{
// remove all entries from prior to Jan 1, 2008
zip1.RemoveEntries("mtime < 2008-01-01");
// don't forget to save the archive!
zip1.Save();
}
Using zip As ZipFile = ZipFile.Read(ZipFileName)
' remove all entries from prior to Jan 1, 2008
zip1.RemoveEntries("mtime < 2008-01-01")
' do not forget to save the archive!
zip1.Save
End Using
using (ZipFile zip1 = ZipFile.Read(ZipFileName))
{
// remove all entries from prior to Jan 1, 2008
zip1.RemoveEntries("mtime < 2008-01-01", "documents");
// a call to ZipFile.Save will make the modifications permanent
zip1.Save();
}
Using zip As ZipFile = ZipFile.Read(ZipFileName)
' remove all entries from prior to Jan 1, 2008
zip1.RemoveEntries("mtime < 2008-01-01", "documents")
' a call to ZipFile.Save will make the modifications permanent
zip1.Save
End Using
using (ZipFile zip = ZipFile.Read(zipArchiveName))
{
zip.ExtractSelectedEntries("name = *.xml and mtime > 2009-01-15");
}
using (ZipFile zip = ZipFile.Read(zipArchiveName))
{
zip.ExtractSelectedEntries("name = *.xml and mtime > 2009-01-15",
ExtractExistingFileAction.OverwriteSilently);
}
using (ZipFile zip = ZipFile.Read(zipArchiveName))
{
zip.ExtractSelectedEntries("name = *.xml and mtime > 2009-01-15","unpack");
}
using (ZipFile zip = ZipFile.Read(zipArchiveName))
{
zip.ExtractSelectedEntries("name = *.xml or size > 100000",
null,
"unpack",
ExtractExistingFileAction.DontOverwrite);
}
string DirectoryPath = "c:\\Documents\\Project7";
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(DirectoryPath, System.IO.Path.GetFileName(DirectoryPath));
zip.Comment = "This will be embedded into a self-extracting console-based exe";
zip.SaveSelfExtractor("archive.exe", SelfExtractorFlavor.ConsoleApplication);
}
Dim DirectoryPath As String = "c:\Documents\Project7"
Using zip As New ZipFile()
zip.AddDirectory(DirectoryPath, System.IO.Path.GetFileName(DirectoryPath))
zip.Comment = "This will be embedded into a self-extracting console-based exe"
zip.SaveSelfExtractor("archive.exe", SelfExtractorFlavor.ConsoleApplication)
End Using
string DirectoryPath = "c:\\Documents\\Project7";
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(DirectoryPath, System.IO.Path.GetFileName(DirectoryPath));
zip.Comment = "This will be embedded into a self-extracting WinForms-based exe";
var options = new SelfExtractorOptions
{
Flavor = SelfExtractorFlavor.WinFormsApplication,
DefaultExtractDirectory = "%USERPROFILE%\\ExtractHere",
PostExtractCommandLine = ExeToRunAfterExtract,
SfxExeWindowTitle = "My Custom Window Title",
RemoveUnpackedFilesAfterExecute = true
};
zip.SaveSelfExtractor("archive.exe", options);
}
Dim DirectoryPath As String = "c:\Documents\Project7"
Using zip As New ZipFile()
zip.AddDirectory(DirectoryPath, System.IO.Path.GetFileName(DirectoryPath))
zip.Comment = "This will be embedded into a self-extracting console-based exe"
Dim options As New SelfExtractorOptions()
options.Flavor = SelfExtractorFlavor.WinFormsApplication
options.DefaultExtractDirectory = "%USERPROFILE%\\ExtractHere"
options.PostExtractCommandLine = ExeToRunAfterExtract
options.SfxExeWindowTitle = "My Custom Window Title"
options.RemoveUnpackedFilesAfterExecute = True
zip.SaveSelfExtractor("archive.exe", options)
End Using
using (ZipFile zip = ZipFile.Read(zipfile))
{
bool header = true;
foreach (ZipEntry e in zip)
{
if (header)
{
System.Console.WriteLine("Zipfile: {0}", zip.Name);
System.Console.WriteLine("Version Needed: 0x{0:X2}", e.VersionNeeded);
System.Console.WriteLine("BitField: 0x{0:X2}", e.BitField);
System.Console.WriteLine("Compression Method: 0x{0:X2}", e.CompressionMethod);
System.Console.WriteLine("\n{1,-22} {2,-6} {3,4} {4,-8} {0}",
"Filename", "Modified", "Size", "Ratio", "Packed");
System.Console.WriteLine(new System.String('-', 72));
header = false;
}
System.Console.WriteLine("{1,-22} {2,-6} {3,4:F0}% {4,-8} {0}",
e.FileName,
e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
e.UncompressedSize,
e.CompressionRatio,
e.CompressedSize);
e.Extract();
}
}
Dim ZipFileToExtract As String = "c:\foo.zip"
Using zip As ZipFile = ZipFile.Read(ZipFileToExtract)
Dim header As Boolean = True
Dim e As ZipEntry
For Each e In zip
If header Then
Console.WriteLine("Zipfile: {0}", zip.Name)
Console.WriteLine("Version Needed: 0x{0:X2}", e.VersionNeeded)
Console.WriteLine("BitField: 0x{0:X2}", e.BitField)
Console.WriteLine("Compression Method: 0x{0:X2}", e.CompressionMethod)
Console.WriteLine(ChrW(10) & "{1,-22} {2,-6} {3,4} {4,-8} {0}", _
"Filename", "Modified", "Size", "Ratio", "Packed" )
Console.WriteLine(New String("-"c, 72))
header = False
End If
Console.WriteLine("{1,-22} {2,-6} {3,4:F0}% {4,-8} {0}", _
e.FileName, _
e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"), _
e.UncompressedSize, _
e.CompressionRatio, _
e.CompressedSize )
e.Extract
Next
End Using
using (var zip = new ZipFile())
{
zip.FullScan = true;
zip.Initialize(zipFileName);
zip.Save(newName);
}
Using zip As New ZipFile
zip.FullScan = True
zip.Initialize(zipFileName)
zip.Save(newName)
End Using
using (var zip = new ZipFile())
{
zip.AddFiles(filesToAdd);
zip.SortEntriesBeforeSaving = true;
zip.Save(name);
}
Using zip As New ZipFile
zip.AddFiles(filesToAdd)
zip.SortEntriesBeforeSaving = True
zip.Save(name)
End Using
using (var zip = new ZipFile())
{
zip.AddDirectoryWillTraverseReparsePoints = false;
zip.AddDirectory(dirToZip,"fodder");
zip.Save(zipFileToCreate);
}
using (ZipFile zip = new ZipFile())
{
zip.SaveProgress += this.zip1_SaveProgress;
zip.AddDirectory(directoryToZip, "");
zip.UseZip64WhenSaving = Zip64Option.Always;
zip.BufferSize = 65536*8; // 65536 * 8 = 512k
zip.Save(ZipFileToCreate);
}
using (var zip = new ZipFile())
{
// produce a zip file the Mac will like
zip.EmitTimesInWindowsFormatWhenSaving = false;
zip.EmitTimesInUnixFormatWhenSaving = true;
zip.AddDirectory(directoryToZip, "files");
zip.Save(outputFile);
}
Using zip As New ZipFile
'' produce a zip file the Mac will like
zip.EmitTimesInWindowsFormatWhenSaving = False
zip.EmitTimesInUnixFormatWhenSaving = True
zip.AddDirectory(directoryToZip, "files")
zip.Save(outputFile)
End Using
using (var zip = ZipFile.Read(zipFileName, System.Text.Encoding.GetEncoding("big5")))
{
// retrieve and extract an entry using a name encoded with CP950
zip[MyDesiredEntry].Extract("unpack");
}
Using zip As ZipFile = ZipFile.Read(ZipToExtract, System.Text.Encoding.GetEncoding("big5"))
' retrieve and extract an entry using a name encoded with CP950
zip(MyDesiredEntry).Extract("unpack")
End Using
using (ZipFile zip= ZipFile.Read(FilePath))
{
zip.StatusMessageTextWriter= System.Console.Out;
// messages are sent to the console during extraction
zip.ExtractAll();
}
Using zip As ZipFile = ZipFile.Read(FilePath)
zip.StatusMessageTextWriter= System.Console.Out
'Status Messages will be sent to the console during extraction
zip.ExtractAll()
End Using
var sw = new System.IO.StringWriter();
using (ZipFile zip= ZipFile.Read(FilePath))
{
zip.StatusMessageTextWriter= sw;
zip.ExtractAll();
}
Console.WriteLine("{0}", sw.ToString());
Dim sw as New System.IO.StringWriter
Using zip As ZipFile = ZipFile.Read(FilePath)
zip.StatusMessageTextWriter= sw
zip.ExtractAll()
End Using
'Status Messages are now available in sw
// create a file with encryption
using (ZipFile zip = new ZipFile())
{
zip.AddFile("ReadMe.txt");
zip.Password= "!Secret1";
zip.AddFile("MapToTheSite-7440-N49th.png");
zip.AddFile("2008-Regional-Sales-Report.pdf");
zip.Save("EncryptedArchive.zip");
}
// extract entries that use encryption
using (ZipFile zip = ZipFile.Read("EncryptedArchive.zip"))
{
zip.Password= "!Secret1";
zip.ExtractAll("extractDir");
}
Using zip As New ZipFile
zip.AddFile("ReadMe.txt")
zip.Password = "123456!"
zip.AddFile("MapToTheSite-7440-N49th.png")
zip.Password= "!Secret1";
zip.AddFile("2008-Regional-Sales-Report.pdf")
zip.Save("EncryptedArchive.zip")
End Using
' extract entries that use encryption
Using (zip as ZipFile = ZipFile.Read("EncryptedArchive.zip"))
zip.Password= "!Secret1"
zip.ExtractAll("extractDir")
End Using
Public Sub SaveZipFile()
Dim SourceFolder As String = "fodder"
Dim DestFile As String = "eHandler.zip"
Dim sw as New StringWriter
Using zipArchive As ZipFile = New ZipFile
' Tell DotNetZip to skip any files for which it encounters an error
zipArchive.ZipErrorAction = ZipErrorAction.Skip
zipArchive.StatusMessageTextWriter = sw
zipArchive.AddDirectory(SourceFolder)
zipArchive.Save(DestFile)
End Using
' examine sw here to see any messages
End Sub
// Create a zip archive with AES Encryption.
using (ZipFile zip = new ZipFile())
{
zip.AddFile("ReadMe.txt");
zip.Encryption= EncryptionAlgorithm.WinZipAes256;
zip.Password= "Top.Secret.No.Peeking!";
zip.AddFile("7440-N49th.png");
zip.AddFile("2008-Regional-Sales-Report.pdf");
zip.Save("EncryptedArchive.zip");
}
// Extract a zip archive that uses AES Encryption.
// You do not need to specify the algorithm during extraction.
using (ZipFile zip = ZipFile.Read("EncryptedArchive.zip"))
{
zip.Password= "Top.Secret.No.Peeking!";
zip.ExtractAll("extractDirectory");
}
' Create a zip that uses Encryption.
Using zip As New ZipFile()
zip.Encryption= EncryptionAlgorithm.WinZipAes256
zip.Password= "Top.Secret.No.Peeking!"
zip.AddFile("ReadMe.txt")
zip.AddFile("7440-N49th.png")
zip.AddFile("2008-Regional-Sales-Report.pdf")
zip.Save("EncryptedArchive.zip")
End Using
' Extract a zip archive that uses AES Encryption.
' You do not need to specify the algorithm during extraction.
Using (zip as ZipFile = ZipFile.Read("EncryptedArchive.zip"))
zip.Password= "Top.Secret.No.Peeking!"
zip.ExtractAll("extractDirectory")
End Using
using (ZipFile zip = ZipFile.Read("PackedDocuments.zip"))
{
foreach (string s1 in zip.EntryFilenames)
{
if (s1.EndsWith(".txt"))
zip[s1].Extract("textfiles");
}
}
Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip")
Dim s1 As String
For Each s1 In zip.EntryFilenames
If s1.EndsWith(".txt") Then
zip(s1).Extract("textfiles")
End If
Next
End Using
String zipFileToRead= "PackedDocuments.zip";
string candidate = "DatedMaterial.xps";
using (ZipFile zip = new ZipFile(zipFileToRead))
{
if (zip.EntryFilenames.Contains(candidate))
Console.WriteLine("The file '{0}' exists in the zip archive '{1}'",
candidate,
zipFileName);
else
Console.WriteLine("The file, '{0}', does not exist in the zip archive '{1}'",
candidate,
zipFileName);
Console.WriteLine();
}
Dim zipFileToRead As String = "PackedDocuments.zip"
Dim candidate As String = "DatedMaterial.xps"
Using zip As ZipFile.Read(ZipFileToRead)
If zip.EntryFilenames.Contains(candidate) Then
Console.WriteLine("The file '{0}' exists in the zip archive '{1}'", _
candidate, _
zipFileName)
Else
Console.WriteLine("The file, '{0}', does not exist in the zip archive '{1}'", _
candidate, _
zipFileName)
End If
Console.WriteLine
End Using
using (ZipFile zip = ZipFile.Read(zipFile))
{
foreach (ZipEntry entry in zip.EntriesSorted)
{
ListViewItem item = new ListViewItem(n.ToString());
n++;
string[] subitems = new string[] {
entry.FileName.Replace("/","\\"),
entry.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
entry.UncompressedSize.ToString(),
String.Format("{0,5:F0}%", entry.CompressionRatio),
entry.CompressedSize.ToString(),
(entry.UsesEncryption) ? "Y" : "N",
String.Format("{0:X8}", entry.Crc)};
foreach (String s in subitems)
{
ListViewItem.ListViewSubItem subitem = new ListViewItem.ListViewSubItem();
subitem.Text = s;
item.SubItems.Add(subitem);
}
this.listView1.Items.Add(item);
}
}
progressBar1.Value = 0;
progressBar1.Max = listbox1.Items.Count;
using (ZipFile zip = new ZipFile())
{
// listbox1 contains a list of filenames
zip.AddFiles(listbox1.Items);
// do the progress bar:
zip.SaveProgress += (sender, e) => {
if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry) {
progressBar1.PerformStep();
}
};
zip.Save(fs);
}
static bool justHadByteUpdate= false;
public static void SaveProgress(object sender, SaveProgressEventArgs e)
{
if (e.EventType == ZipProgressEventType.Saving_Started)
Console.WriteLine("Saving: {0}", e.ArchiveName);
else if (e.EventType == ZipProgressEventType.Saving_Completed)
{
justHadByteUpdate= false;
Console.WriteLine();
Console.WriteLine("Done: {0}", e.ArchiveName);
}
else if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry)
{
if (justHadByteUpdate)
Console.WriteLine();
Console.WriteLine(" Writing: {0} ({1}/{2})",
e.CurrentEntry.FileName, e.EntriesSaved, e.EntriesTotal);
justHadByteUpdate= false;
}
else if (e.EventType == ZipProgressEventType.Saving_EntryBytesRead)
{
if (justHadByteUpdate)
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, e.TotalBytesToTransfer,
e.BytesTransferred / (0.01 * e.TotalBytesToTransfer ));
justHadByteUpdate= true;
}
}
public static ZipUp(string targetZip, string directory)
{
using (var zip = new ZipFile()) {
zip.SaveProgress += SaveProgress;
zip.AddDirectory(directory);
zip.Save(targetZip);
}
}
Public Sub ZipUp(ByVal targetZip As String, ByVal directory As String)
Using zip As ZipFile = New ZipFile
AddHandler zip.SaveProgress, AddressOf MySaveProgress
zip.AddDirectory(directory)
zip.Save(targetZip)
End Using
End Sub
Private Shared justHadByteUpdate As Boolean = False
Public Shared Sub MySaveProgress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
If (e.EventType Is ZipProgressEventType.Saving_Started) Then
Console.WriteLine("Saving: {0}", e.ArchiveName)
ElseIf (e.EventType Is ZipProgressEventType.Saving_Completed) Then
justHadByteUpdate = False
Console.WriteLine
Console.WriteLine("Done: {0}", e.ArchiveName)
ElseIf (e.EventType Is ZipProgressEventType.Saving_BeforeWriteEntry) Then
If justHadByteUpdate Then
Console.WriteLine
End If
Console.WriteLine(" Writing: {0} ({1}/{2})", e.CurrentEntry.FileName, e.EntriesSaved, e.EntriesTotal)
justHadByteUpdate = False
ElseIf (e.EventType Is ZipProgressEventType.Saving_EntryBytesRead) Then
If justHadByteUpdate Then
Console.SetCursorPosition(0, Console.CursorTop)
End If
Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, _
e.TotalBytesToTransfer, _
(CDbl(e.BytesTransferred) / (0.01 * e.TotalBytesToTransfer)))
justHadByteUpdate = True
End If
End Sub
delegate void SaveEntryProgress(SaveProgressEventArgs e);
delegate void ButtonClick(object sender, EventArgs e);
public class WorkerOptions
{
public string ZipName;
public string Folder;
public string Encoding;
public string Comment;
public int ZipFlavor;
public Zip64Option Zip64;
}
private int _progress2MaxFactor;
private bool _saveCanceled;
private long _totalBytesBeforeCompress;
private long _totalBytesAfterCompress;
private Thread _workerThread;
private void btnZipup_Click(object sender, EventArgs e)
{
KickoffZipup();
}
private void btnCancel_Click(object sender, EventArgs e)
{
if (this.lblStatus.InvokeRequired)
{
this.lblStatus.Invoke(new ButtonClick(this.btnCancel_Click), new object[] { sender, e });
}
else
{
_saveCanceled = true;
lblStatus.Text = "Canceled...";
ResetState();
}
}
private void KickoffZipup()
{
_folderName = tbDirName.Text;
if (_folderName == null || _folderName == "") return;
if (this.tbZipName.Text == null || this.tbZipName.Text == "") return;
// check for existence of the zip file:
if (System.IO.File.Exists(this.tbZipName.Text))
{
var dlgResult = MessageBox.Show(String.Format("The file you have specified ({0}) already exists." +
" Do you want to overwrite this file?", this.tbZipName.Text),
"Confirmation is Required", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dlgResult != DialogResult.Yes) return;
System.IO.File.Delete(this.tbZipName.Text);
}
_saveCanceled = false;
_nFilesCompleted = 0;
_totalBytesAfterCompress = 0;
_totalBytesBeforeCompress = 0;
this.btnOk.Enabled = false;
this.btnOk.Text = "Zipping...";
this.btnCancel.Enabled = true;
lblStatus.Text = "Zipping...";
var options = new WorkerOptions
{
ZipName = this.tbZipName.Text,
Folder = _folderName,
Encoding = "ibm437"
};
if (this.comboBox1.SelectedIndex != 0)
{
options.Encoding = this.comboBox1.SelectedItem.ToString();
}
if (this.radioFlavorSfxCmd.Checked)
options.ZipFlavor = 2;
else if (this.radioFlavorSfxGui.Checked)
options.ZipFlavor = 1;
else options.ZipFlavor = 0;
if (this.radioZip64AsNecessary.Checked)
options.Zip64 = Zip64Option.AsNecessary;
else if (this.radioZip64Always.Checked)
options.Zip64 = Zip64Option.Always;
else options.Zip64 = Zip64Option.Never;
options.Comment = String.Format("Encoding:{0} || Flavor:{1} || ZIP64:{2}\r\nCreated at {3} || {4}\r\n",
options.Encoding,
FlavorToString(options.ZipFlavor),
options.Zip64.ToString(),
System.DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss"),
this.Text);
if (this.tbComment.Text != TB_COMMENT_NOTE)
options.Comment += this.tbComment.Text;
_workerThread = new Thread(this.DoSave);
_workerThread.Name = "Zip Saver thread";
_workerThread.Start(options);
this.Cursor = Cursors.WaitCursor;
}
private void DoSave(Object p)
{
WorkerOptions options = p as WorkerOptions;
try
{
using (var zip1 = new ZipFile())
{
zip1.ProvisionalAlternateEncoding = System.Text.Encoding.GetEncoding(options.Encoding);
zip1.Comment = options.Comment;
zip1.AddDirectory(options.Folder);
_entriesToZip = zip1.EntryFileNames.Count;
SetProgressBars();
zip1.SaveProgress += this.zip1_SaveProgress;
zip1.UseZip64WhenSaving = options.Zip64;
if (options.ZipFlavor == 1)
zip1.SaveSelfExtractor(options.ZipName, SelfExtractorFlavor.WinFormsApplication);
else if (options.ZipFlavor == 2)
zip1.SaveSelfExtractor(options.ZipName, SelfExtractorFlavor.ConsoleApplication);
else
zip1.Save(options.ZipName);
}
}
catch (System.Exception exc1)
{
MessageBox.Show(String.Format("Exception while zipping: {0}", exc1.Message));
btnCancel_Click(null, null);
}
}
void zip1_SaveProgress(object sender, SaveProgressEventArgs e)
{
switch (e.EventType)
{
case ZipProgressEventType.Saving_AfterWriteEntry:
StepArchiveProgress(e);
break;
case ZipProgressEventType.Saving_EntryBytesRead:
StepEntryProgress(e);
break;
case ZipProgressEventType.Saving_Completed:
SaveCompleted();
break;
case ZipProgressEventType.Saving_AfterSaveTempArchive:
// this event only occurs when saving an SFX file
TempArchiveSaved();
break;
}
if (_saveCanceled)
e.Cancel = true;
}
private void StepArchiveProgress(SaveProgressEventArgs e)
{
if (this.progressBar1.InvokeRequired)
{
this.progressBar1.Invoke(new SaveEntryProgress(this.StepArchiveProgress), new object[] { e });
}
else
{
if (!_saveCanceled)
{
_nFilesCompleted++;
this.progressBar1.PerformStep();
_totalBytesAfterCompress += e.CurrentEntry.CompressedSize;
_totalBytesBeforeCompress += e.CurrentEntry.UncompressedSize;
// reset the progress bar for the entry:
this.progressBar2.Value = this.progressBar2.Maximum = 1;
this.Update();
}
}
}
private void StepEntryProgress(SaveProgressEventArgs e)
{
if (this.progressBar2.InvokeRequired)
{
this.progressBar2.Invoke(new SaveEntryProgress(this.StepEntryProgress), new object[] { e });
}
else
{
if (!_saveCanceled)
{
if (this.progressBar2.Maximum == 1)
{
// reset
Int64 max = e.TotalBytesToTransfer;
_progress2MaxFactor = 0;
while (max > System.Int32.MaxValue)
{
max /= 2;
_progress2MaxFactor++;
}
this.progressBar2.Maximum = (int)max;
lblStatus.Text = String.Format("{0} of {1} files...({2})",
_nFilesCompleted + 1, _entriesToZip, e.CurrentEntry.FileName);
}
int xferred = e.BytesTransferred >> _progress2MaxFactor;
this.progressBar2.Value = (xferred >= this.progressBar2.Maximum)
? this.progressBar2.Maximum
: xferred;
this.Update();
}
}
}
private void SaveCompleted()
{
if (this.lblStatus.InvokeRequired)
{
this.lblStatus.Invoke(new MethodInvoker(this.SaveCompleted));
}
else
{
lblStatus.Text = String.Format("Done, Compressed {0} files, {1:N0}% of original.",
_nFilesCompleted, (100.00 * _totalBytesAfterCompress) / _totalBytesBeforeCompress);
ResetState();
}
}
private void ResetState()
{
this.btnCancel.Enabled = false;
this.btnOk.Enabled = true;
this.btnOk.Text = "Zip it!";
this.progressBar1.Value = 0;
this.progressBar2.Value = 0;
this.Cursor = Cursors.Default;
if (!_workerThread.IsAlive)
_workerThread.Join();
}
private static bool justHadByteUpdate = false;
public static void ExtractProgress(object sender, ExtractProgressEventArgs e)
{
if(e.EventType == ZipProgressEventType.Extracting_EntryBytesWritten)
{
if (justHadByteUpdate)
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, e.TotalBytesToTransfer,
e.BytesTransferred / (0.01 * e.TotalBytesToTransfer ));
justHadByteUpdate = true;
}
else if(e.EventType == ZipProgressEventType.Extracting_BeforeExtractEntry)
{
if (justHadByteUpdate)
Console.WriteLine();
Console.WriteLine("Extracting: {0}", e.CurrentEntry.FileName);
justHadByteUpdate= false;
}
}
public static ExtractZip(string zipToExtract, string directory)
{
string TargetDirectory= "extract";
using (var zip = ZipFile.Read(zipToExtract)) {
zip.ExtractProgress += ExtractProgress;
foreach (var e in zip1)
{
e.Extract(TargetDirectory, true);
}
}
}
Public Shared Sub Main(ByVal args As String())
Dim ZipToUnpack As String = "C1P3SML.zip"
Dim TargetDir As String = "ExtractTest_Extract"
Console.WriteLine("Extracting file {0} to {1}", ZipToUnpack, TargetDir)
Using zip1 As ZipFile = ZipFile.Read(ZipToUnpack)
AddHandler zip1.ExtractProgress, AddressOf MyExtractProgress
Dim e As ZipEntry
For Each e In zip1
e.Extract(TargetDir, True)
Next
End Using
End Sub
Private Shared justHadByteUpdate As Boolean = False
Public Shared Sub MyExtractProgress(ByVal sender As Object, ByVal e As ExtractProgressEventArgs)
If (e.EventType = ZipProgressEventType.Extracting_EntryBytesWritten) Then
If ExtractTest.justHadByteUpdate Then
Console.SetCursorPosition(0, Console.CursorTop)
End If
Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, e.TotalBytesToTransfer, (CDbl(e.BytesTransferred) / (0.01 * e.TotalBytesToTransfer)))
ExtractTest.justHadByteUpdate = True
ElseIf (e.EventType = ZipProgressEventType.Extracting_BeforeExtractEntry) Then
If ExtractTest.justHadByteUpdate Then
Console.WriteLine
End If
Console.WriteLine("Extracting: {0}", e.CurrentEntry.FileName)
ExtractTest.justHadByteUpdate = False
End If
End Sub
int _numEntriesToAdd= 0;
int _numEntriesAdded= 0;
void AddProgressHandler(object sender, AddProgressEventArgs e)
{
switch (e.EventType)
{
case ZipProgressEventType.Adding_Started:
Console.WriteLine("Adding files to the zip...");
break;
case ZipProgressEventType.Adding_AfterAddEntry:
_numEntriesAdded++;
Console.WriteLine(String.Format("Adding file {0}/{1} :: {2}",
_numEntriesAdded, _numEntriesToAdd, e.CurrentEntry.FileName));
break;
case ZipProgressEventType.Adding_Completed:
Console.WriteLine("Added all files");
break;
}
}
void CreateTheZip()
{
using (ZipFile zip = new ZipFile())
{
zip.AddProgress += AddProgressHandler;
zip.AddDirectory(System.IO.Path.GetFileName(DirToZip));
zip.Save(ZipFileToCreate);
}
}
Private Sub AddProgressHandler(ByVal sender As Object, ByVal e As AddProgressEventArgs)
Select Case e.EventType
Case ZipProgressEventType.Adding_Started
Console.WriteLine("Adding files to the zip...")
Exit Select
Case ZipProgressEventType.Adding_AfterAddEntry
Console.WriteLine(String.Format("Adding file {0}", e.CurrentEntry.FileName))
Exit Select
Case ZipProgressEventType.Adding_Completed
Console.WriteLine("Added all files")
Exit Select
End Select
End Sub
Sub CreateTheZip()
Using zip as ZipFile = New ZipFile
AddHandler zip.AddProgress, AddressOf AddProgressHandler
zip.AddDirectory(System.IO.Path.GetFileName(DirToZip))
zip.Save(ZipFileToCreate);
End Using
End Sub
public static void MyZipError(object sender, ZipErrorEventArgs e)
{
Console.WriteLine("Error saving {0}...", e.FileName);
Console.WriteLine(" Exception: {0}", e.exception);
ZipEntry entry = e.CurrentEntry;
string response = null;
// Ask the user whether he wants to skip this error or not
do
{
Console.Write("Retry, Skip, Throw, or Cancel ? (R/S/T/C) ");
response = Console.ReadLine();
Console.WriteLine();
} while (response != null &&
response[0]!='S' && response[0]!='s' &&
response[0]!='R' && response[0]!='r' &&
response[0]!='T' && response[0]!='t' &&
response[0]!='C' && response[0]!='c');
e.Cancel = (response[0]=='C' || response[0]=='c');
if (response[0]=='S' || response[0]=='s')
entry.ZipErrorAction = ZipErrorAction.Skip;
else if (response[0]=='R' || response[0]=='r')
entry.ZipErrorAction = ZipErrorAction.Retry;
else if (response[0]=='T' || response[0]=='t')
entry.ZipErrorAction = ZipErrorAction.Throw;
}
public void SaveTheFile()
{
string directoryToZip = "fodder";
string directoryInArchive = "files";
string zipFileToCreate = "Archive.zip";
using (var zip = new ZipFile())
{
// set the event handler before adding any entries
zip.ZipError += MyZipError;
zip.AddDirectory(directoryToZip, directoryInArchive);
zip.Save(zipFileToCreate);
}
}
Private Sub MyZipError(ByVal sender As Object, ByVal e As Ionic.Zip.ZipErrorEventArgs)
' At this point, the application could prompt the user for an action to take.
' But in this case, this application will simply automatically skip the file, in case of error.
Console.WriteLine("Zip Error, entry {0}", e.CurrentEntry.FileName)
Console.WriteLine(" Exception: {0}", e.exception)
' set the desired ZipErrorAction on the CurrentEntry to communicate that to DotNetZip
e.CurrentEntry.ZipErrorAction = Zip.ZipErrorAction.Skip
End Sub
Public Sub SaveTheFile()
Dim directoryToZip As String = "fodder"
Dim directoryInArchive As String = "files"
Dim zipFileToCreate as String = "Archive.zip"
Using zipArchive As ZipFile = New ZipFile
' set the event handler before adding any entries
AddHandler zipArchive.ZipError, AddressOf MyZipError
zipArchive.AddDirectory(directoryToZip, directoryInArchive)
zipArchive.Save(zipFileToCreate)
End Using
End Sub
This is the version using unrolled loops.
var fname = "logfile.log.bz2";
using (var fs = File.OpenRead(fname))
{
using (var decompressor = new Ionic.BZip2.BZip2InputStream(fs))
{
var outFname = fname + ".decompressed";
using (var output = File.Create(outFname))
{
byte[] buffer = new byte[2048];
int n;
while ((n = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, n);
}
}
}
}
var fname = "logfile.log";
using (var fs = File.OpenRead(fname))
{
var outFname = fname + ".bz2";
using (var output = File.Create(outFname))
{
using (var compressor = new Ionic.BZip2.BZip2OutputStream(output))
{
byte[] buffer = new byte[2048];
int n;
while ((n = fs.Read(buffer, 0, buffer.Length)) > 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
var fname = "logfile.log";
using (var fs = File.OpenRead(fname))
{
var outFname = fname + ".bz2";
using (var output = File.Create(outFname))
{
using (var compressor = new Ionic.BZip2.ParallelBZip2OutputStream(output))
{
byte[] buffer = new byte[2048];
int n;
while ((n = fs.Read(buffer, 0, buffer.Length)) > 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
{
using (Stream compressor = new DeflateStream(raw, CompressionMode.Compress))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".deflated")
Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
{
using (Stream compressor = new DeflateStream(raw,
CompressionMode.Compress,
CompressionLevel.BestCompression))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n= -1;
while (n != 0)
{
if (n > 0)
compressor.Write(buffer, 0, n);
n= input.Read(buffer, 0, buffer.Length);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".deflated")
Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
using (var output = System.IO.File.Create(fileToCompress + ".deflated"))
{
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (Stream compressor = new DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n= -1;
while (n != 0)
{
if (n > 0)
compressor.Write(buffer, 0, n);
n= input.Read(buffer, 0, buffer.Length);
}
}
}
// can write additional data to the output stream here
}
Using output As FileStream = File.Create(fileToCompress & ".deflated")
Using input As Stream = File.OpenRead(fileToCompress)
Using compressor As Stream = New DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
' can write additional data to the output stream here.
End Using
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(outputFile))
{
using (Stream compressor = new GZipStream(raw, CompressionMode.Compress))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Dim outputFile As String = (fileToCompress & ".compressed")
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(outputFile)
Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
private void GunZipFile(string filename)
{
if (!filename.EndsWith(".gz))
throw new ArgumentException("filename");
var DecompressedFile = filename.Substring(0,filename.Length-3);
byte[] working = new byte[WORKING_BUFFER_SIZE];
int n= 1;
using (System.IO.Stream input = System.IO.File.OpenRead(filename))
{
using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
{
using (var output = System.IO.File.Create(DecompressedFile))
{
while (n !=0)
{
n= decompressor.Read(working, 0, working.Length);
if (n > 0)
{
output.Write(working, 0, n);
}
}
}
}
}
}
Private Sub GunZipFile(ByVal filename as String)
If Not (filename.EndsWith(".gz)) Then
Throw New ArgumentException("filename")
End If
Dim DecompressedFile as String = filename.Substring(0,filename.Length-3)
Dim working(WORKING_BUFFER_SIZE) as Byte
Dim n As Integer = 1
Using input As Stream = File.OpenRead(filename)
Using decompressor As Stream = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, True)
Using output As Stream = File.Create(UncompressedFile)
Do
n= decompressor.Read(working, 0, working.Length)
If n > 0 Then
output.Write(working, 0, n)
End IF
Loop While (n > 0)
End Using
End Using
End Using
End Sub
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".gz"))
{
using (Stream compressor = new GZipStream(raw,
CompressionMode.Compress,
CompressionLevel.BestCompression))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".gz")
Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(outputFile))
{
using (Stream compressor = new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Dim outputFile As String = (fileToCompress & ".compressed")
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(outputFile)
Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, True)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
byte[] working = new byte[WORKING_BUFFER_SIZE];
using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile))
{
using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
{
using (var output = System.IO.File.Create(_DecompressedFile))
{
int n;
while ((n= decompressor.Read(working, 0, working.Length)) !=0)
{
output.Write(working, 0, n);
}
}
}
}
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n= -1;
String outputFile = fileToCompress + ".compressed";
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(outputFile))
{
using (Stream compressor = new ParallelDeflateOutputStream(raw))
{
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Dim outputFile As String = (fileToCompress & ".compressed")
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(outputFile)
Using compressor As Stream = New ParallelDeflateOutputStream(raw)
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
ParallelDeflateOutputStream deflater = null;
foreach (var inputFile in listOfFiles)
{
string outputFile = inputFile + ".compressed";
using (System.IO.Stream input = System.IO.File.OpenRead(inputFile))
{
using (var outStream = System.IO.File.Create(outputFile))
{
if (deflater == null)
deflater = new ParallelDeflateOutputStream(outStream,
CompressionLevel.Best,
CompressionStrategy.Default,
true);
deflater.Reset(outStream);
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
deflater.Write(buffer, 0, n);
}
}
}
}
var adler = Adler.Adler32(0, null, 0, 0);
adler = Adler.Adler32(adler, buffer, index, length);
private void InflateBuffer()
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
ZlibCodec decompressor = new ZlibCodec();
Console.WriteLine("\n============================================");
Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length);
MemoryStream ms = new MemoryStream(DecompressedBytes);
int rc = decompressor.InitializeInflate();
decompressor.InputBuffer = CompressedBytes;
decompressor.NextIn = 0;
decompressor.AvailableBytesIn = CompressedBytes.Length;
decompressor.OutputBuffer = buffer;
// pass 1: inflate
do
{
decompressor.NextOut = 0;
decompressor.AvailableBytesOut = buffer.Length;
rc = decompressor.Inflate(FlushType.None);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new Exception("inflating: " + decompressor.Message);
ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut);
}
while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
// pass 2: finish and flush
do
{
decompressor.NextOut = 0;
decompressor.AvailableBytesOut = buffer.Length;
rc = decompressor.Inflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("inflating: " + decompressor.Message);
if (buffer.Length - decompressor.AvailableBytesOut > 0)
ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut);
}
while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
decompressor.EndInflate();
}
int bufferSize = 40000;
byte[] CompressedBytes = new byte[bufferSize];
byte[] DecompressedBytes = new byte[bufferSize];
ZlibCodec compressor = new ZlibCodec();
compressor.InitializeDeflate(CompressionLevel.Default);
compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);
compressor.NextIn = 0;
compressor.AvailableBytesIn = compressor.InputBuffer.Length;
compressor.OutputBuffer = CompressedBytes;
compressor.NextOut = 0;
compressor.AvailableBytesOut = CompressedBytes.Length;
while (compressor.TotalBytesIn != TextToCompress.Length && compressor.TotalBytesOut < bufferSize)
{
compressor.Deflate(FlushType.None);
}
while (true)
{
int rc= compressor.Deflate(FlushType.Finish);
if (rc == ZlibConstants.Z_STREAM_END) break;
}
compressor.EndDeflate();
private void DeflateBuffer(CompressionLevel level)
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
ZlibCodec compressor = new ZlibCodec();
Console.WriteLine("\n============================================");
Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length);
MemoryStream ms = new MemoryStream();
int rc = compressor.InitializeDeflate(level);
compressor.InputBuffer = UncompressedBytes;
compressor.NextIn = 0;
compressor.AvailableBytesIn = UncompressedBytes.Length;
compressor.OutputBuffer = buffer;
// pass 1: deflate
do
{
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.None);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new Exception("deflating: " + compressor.Message);
ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut);
}
while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
// pass 2: finish and flush
do
{
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("deflating: " + compressor.Message);
if (buffer.Length - compressor.AvailableBytesOut > 0)
ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
}
while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
compressor.EndDeflate();
ms.Seek(0, SeekOrigin.Begin);
CompressedBytes = new byte[compressor.TotalBytesOut];
ms.Read(CompressedBytes, 0, CompressedBytes.Length);
}
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
{
using (Stream compressor = new ZlibStream(raw, CompressionMode.Compress))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".zlib")
Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
{
using (Stream compressor = new ZlibStream(raw,
CompressionMode.Compress,
CompressionLevel.BestCompression))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".zlib")
Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
using (var output = System.IO.File.Create(fileToCompress + ".zlib"))
{
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (Stream compressor = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
// can write additional data to the output stream here
}
Using output As FileStream = File.Create(fileToCompress & ".zlib")
Using input As Stream = File.OpenRead(fileToCompress)
Using compressor As Stream = New ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
' can write additional data to the output stream here.
End Using