Step-by-Step Guide: Integrating ZipStorer into Your C# Project
1) What ZipStorer is
ZipStorer is a small, single-file C# library for creating and extracting ZIP archives with minimal dependencies and a straightforward API.
2) Quick prerequisites
- .NET project (Framework or .NET Core/.NET 5+)
- Basic C# knowledge
- A copy of the ZipStorer.cs source (usually from the project GitHub or a NuGet package if available)
3) Add ZipStorer to your project
- Download ZipStorer.cs from the repository or install a NuGet package (if one exists).
- Add the ZipStorer.cs file to your project (right-click project → Add → Existing Item, or place in your source folder and include in the project file).
- Add
usingif needed (no special namespace required if the file has none).
4) Create a ZIP archive (example)
- Open a ZipStorer archive for writing:
csharp
using (var zip = ZipStorer.Create(“archive.zip”, “Created by ZipStorer”)){ // add a file from disk zip.AddFile(ZipStorer.Compression.Store, “path/to/file.txt”, “file.txt”, “file description”); // add data from a stream or byte[]: using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(“hello”))) { zip.AddStream(ZipStorer.Compression.Deflate, ms, “greeting.txt”, “inline text file”); }}
- Choose Compression.Store (no compression) or Compression.Deflate.
5) Extract files from a ZIP
csharp
using (var zip = ZipStorer.Open(“archive.zip”, FileAccess.Read)){ var dir = zip.ReadCentralDir(); foreach (var entry in dir) { // extract to disk zip.ExtractFile(entry, Path.Combine(“out”, entry.FilenameInZip)); }}
6) Read a single file to memory
csharp
using (var zip = ZipStorer.Open(“archive.zip”, FileAccess.Read)){ var dir = zip.ReadCentralDir(); var entry = dir.First(e => e.FilenameInZip == “greeting.txt”); using (var ms = new MemoryStream()) { zip.ExtractFile(entry, ms); string text = Encoding.UTF8.GetString(ms.ToArray()); }}
7) Common pitfalls & tips
- Ensure correct FileAccess when opening (Read vs ReadWrite).
- Use Deflate for better size reduction; Store for speed or already-compressed files.
- Filenames in the archive are case-sensitive when matching entries.
- When adding streams, reset Position to 0 before calling AddStream.
- For large files, extract directly to disk instead of memory to avoid high RAM use.
8) Troubleshooting
- “Invalid zip” errors: confirm the file wasn’t partially written and you opened with correct access.
- Corrupted extraction: check if streams were disposed or positions reset incorrectly.
9) Further resources
- Consult the ZipStorer source comments and examples in the repository for advanced usage (multi-file adds, comments, timestamps).
Leave a Reply