Chapter100:Readingandwriting.zipfiles

No Comments

Parameter                                                                          Details

archiveFileName Thepathtothearchivetoopen,specifiedasarelativeorabsolutepath.Arelativepathis interpreted as relative to the current working directory.

Section100.1:Writingtoazipfile

Towriteanew.zipfile:

System.IO.Compression

System.IO.Compression.FileSystem

using(FileStreamzipToOpen=newFileStream(@”C:\temp”,FileMode.Open))

{

using(ZipArchivearchive=newZipArchive(zipToOpen,ZipArchiveMode.Update))

{

ZipArchiveEntryreadmeEntry=archive.CreateEntry(“Readme.txt”); using(StreamWriterwriter=newStreamWriter(readmeEntry.Open()))

{

writer.WriteLine(“Informationaboutthispackage.”);

writer.WriteLine(“========================”);

}

}

}

Section100.2:WritingZipFilesin-memory

Thefollowingexamplewillreturnthebyte[]dataofazippedfilecontainingthefilesprovidedtoit,without needingaccesstothefilesystem.

publicstaticbyte[]ZipFiles(Dictionary<string,byte[]>files)

{

using(MemoryStreamms=newMemoryStream())

{

using(ZipArchivearchive=newZipArchive(ms,ZipArchiveMode.Update))

{

foreach(varfileinfiles)

{

ZipArchiveEntryorderEntry=archive.CreateEntry(file.Key);//createafilewith

thisname

using(BinaryWriterwriter=newBinaryWriter(orderEntry.Open()))

{

writer.Write(file.Value);//writethebinarydata

}

}

}

//ZipArchivemustbedisposedbeforetheMemoryStreamhasdata

returnms.ToArray();

}

}

Section100.3:GetfilesfromaZipfile

Thisexamplegetsalistingoffilesfromtheprovidedziparchivebinary data:

publicstaticDictionary<string,byte[]>GetFiles(byte[]zippedFile)

{

using(MemoryStreamms=newMemoryStream(zippedFile))

using(ZipArchivearchive=newZipArchive(ms,ZipArchiveMode.Read))

{

returnarchive.Entries.ToDictionary(x=>x.FullName,x=>ReadStream(x.Open()));

}

}

privatestaticbyte[]ReadStream(Streamstream)

{

using(varms=newMemoryStream())

{

stream.CopyTo(ms);

returnms.ToArray();

}

}

Section100.4:Thefollowingexampleshowshowtoopenazip archiveandextractall.txtfilestoafolder

usingSystem;

usingSystem.IO;

usingSystem.IO.Compression;

namespaceConsoleApplication1

{

classProgram

{

staticvoidMain(string[]args)

{

stringzipPath=@”c:\example\start.zip”;

stringextractPath=@”c:\example\extract”;

using(ZipArchivearchive=ZipFile.OpenRead(zipPath))

{

foreach(ZipArchiveEntryentryinarchive.Entries)

{

if(entry.FullName.EndsWith(“.txt”,StringComparison.OrdinalIgnoreCase))

{

entry.ExtractToFile(Path.Combine(extractPath,entry.FullName));

}

}

}

}

}

}

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Leave a Comment