Files
sharpcompress/docs/API.md

513 lines
12 KiB
Markdown
Raw Normal View History

2026-01-08 15:34:48 +00:00
# API Quick Reference
Quick reference for commonly used SharpCompress APIs.
## Factory Methods
### Opening Archives
```csharp
// Auto-detect format
2026-01-15 13:29:57 +00:00
using (var reader = ReaderFactory.OpenReader(stream))
2026-01-08 15:34:48 +00:00
{
// Works with Zip, Tar, GZip, Rar, 7Zip, etc.
}
// Specific format - Archive API
2026-01-15 13:29:57 +00:00
using (var archive = ZipArchive.OpenArchive("file.zip"))
using (var archive = TarArchive.OpenArchive("file.tar"))
using (var archive = RarArchive.OpenArchive("file.rar"))
using (var archive = SevenZipArchive.OpenArchive("file.7z"))
using (var archive = GZipArchive.OpenArchive("file.gz"))
2026-01-08 15:34:48 +00:00
// With options
2026-01-12 16:08:16 +00:00
var options = new ReaderOptions
{
2026-01-08 15:34:48 +00:00
Password = "password",
LeaveStreamOpen = true,
ArchiveEncoding = new ArchiveEncoding { Default = Encoding.GetEncoding(932) }
};
2026-01-15 13:29:57 +00:00
using (var archive = ZipArchive.OpenArchive("encrypted.zip", options))
2026-01-08 15:34:48 +00:00
```
### Creating Archives
```csharp
// Writer Factory
2026-01-15 13:29:57 +00:00
using (var writer = WriterFactory.OpenWriter(stream, ArchiveType.Zip, CompressionType.Deflate))
2026-01-08 15:34:48 +00:00
{
// Write entries
}
// Specific writer
2026-01-15 13:04:09 +00:00
using (var archive = ZipArchive.CreateArchive())
using (var archive = TarArchive.CreateArchive())
using (var archive = GZipArchive.CreateArchive())
2026-01-08 15:34:48 +00:00
// With options
2026-01-15 13:04:09 +00:00
var options = new WriterOptions(CompressionType.Deflate)
{
2026-01-08 15:34:48 +00:00
CompressionLevel = 9,
LeaveStreamOpen = false
};
2026-01-15 13:04:09 +00:00
using (var archive = ZipArchive.CreateArchive())
2026-01-08 15:34:48 +00:00
{
archive.SaveTo("output.zip", options);
}
```
---
## Archive API Methods
### Reading/Extracting
```csharp
2026-01-15 13:29:57 +00:00
using (var archive = ZipArchive.OpenArchive("file.zip"))
2026-01-08 15:34:48 +00:00
{
// Get all entries
2026-01-12 16:08:16 +00:00
IEnumerable<IArchiveEntry> entries = archive.Entries;
2026-01-08 15:34:48 +00:00
// Find specific entry
var entry = archive.Entries.FirstOrDefault(e => e.Key == "file.txt");
2026-01-12 16:08:16 +00:00
2026-01-08 15:34:48 +00:00
// Extract all
archive.WriteToDirectory(@"C:\output", new ExtractionOptions
{
ExtractFullPath = true,
Overwrite = true
});
2026-01-12 16:08:16 +00:00
2026-01-08 15:34:48 +00:00
// Extract single entry
var entry = archive.Entries.First();
entry.WriteToFile(@"C:\output\file.txt");
entry.WriteToFile(@"C:\output\file.txt", new ExtractionOptions { Overwrite = true });
2026-01-12 16:08:16 +00:00
2026-01-08 15:34:48 +00:00
// Get entry stream
using (var stream = entry.OpenEntryStream())
{
stream.CopyTo(outputStream);
}
}
2026-01-12 16:08:16 +00:00
// Async extraction (requires IAsyncArchive)
2026-01-15 13:04:09 +00:00
using (var asyncArchive = await ZipArchive.OpenAsyncArchive("file.zip"))
2026-01-12 16:08:16 +00:00
{
await asyncArchive.WriteToDirectoryAsync(
@"C:\output",
new ExtractionOptions { ExtractFullPath = true, Overwrite = true },
cancellationToken: cancellationToken
);
}
2026-01-08 15:34:48 +00:00
using (var stream = await entry.OpenEntryStreamAsync(cancellationToken))
{
// ...
}
```
### Entry Properties
```csharp
foreach (var entry in archive.Entries)
{
string name = entry.Key; // Entry name/path
long size = entry.Size; // Uncompressed size
long compressedSize = entry.CompressedSize;
bool isDir = entry.IsDirectory;
DateTime? modTime = entry.LastModifiedTime;
CompressionType compression = entry.CompressionType;
}
```
### Creating Archives
```csharp
2026-01-15 13:04:09 +00:00
using (var archive = ZipArchive.CreateArchive())
2026-01-08 15:34:48 +00:00
{
// Add file
2026-01-12 16:08:16 +00:00
archive.AddEntry("file.txt", @"C:\source\file.txt");
2026-01-08 15:34:48 +00:00
// Add multiple files
2026-01-12 16:08:16 +00:00
archive.AddAllFromDirectory(@"C:\source");
archive.AddAllFromDirectory(@"C:\source", "*.txt"); // Pattern
2026-01-08 15:34:48 +00:00
// Save to file
archive.SaveTo("output.zip", CompressionType.Deflate);
2026-01-12 16:08:16 +00:00
2026-01-08 15:34:48 +00:00
// Save to stream
archive.SaveTo(outputStream, new WriterOptions(CompressionType.Deflate)
{
CompressionLevel = 9,
LeaveStreamOpen = true
});
}
```
---
## Reader API Methods
### Forward-Only Reading
```csharp
using (var stream = File.OpenRead("file.zip"))
2026-01-15 13:29:57 +00:00
using (var reader = ReaderFactory.OpenReader(stream))
2026-01-08 15:34:48 +00:00
{
while (reader.MoveToNextEntry())
{
2026-01-12 16:08:16 +00:00
IArchiveEntry entry = reader.Entry;
2026-01-08 15:34:48 +00:00
if (!entry.IsDirectory)
{
// Extract entry
reader.WriteEntryToDirectory(@"C:\output");
reader.WriteEntryToFile(@"C:\output\file.txt");
2026-01-12 16:08:16 +00:00
2026-01-08 15:34:48 +00:00
// Or get stream
using (var entryStream = reader.OpenEntryStream())
{
entryStream.CopyTo(outputStream);
}
}
}
}
2026-01-15 13:04:09 +00:00
// Async variants (use OpenAsyncReader to get IAsyncReader)
2026-01-12 16:08:16 +00:00
using (var stream = File.OpenRead("file.zip"))
2026-01-15 13:04:09 +00:00
using (var reader = await ReaderFactory.OpenAsyncReader(stream))
2026-01-08 15:34:48 +00:00
{
2026-01-12 16:08:16 +00:00
while (await reader.MoveToNextEntryAsync())
{
await reader.WriteEntryToFileAsync(
@"C:\output\" + reader.Entry.Key,
cancellationToken: cancellationToken
);
}
2026-01-08 15:34:48 +00:00
2026-01-12 16:08:16 +00:00
// Async extraction of all entries
await reader.WriteAllToDirectoryAsync(
@"C:\output",
new ExtractionOptions { ExtractFullPath = true, Overwrite = true },
cancellationToken
);
}
2026-01-08 15:34:48 +00:00
```
---
## Writer API Methods
### Creating Archives (Streaming)
```csharp
using (var stream = File.Create("output.zip"))
2026-01-15 13:29:57 +00:00
using (var writer = WriterFactory.OpenWriter(stream, ArchiveType.Zip, CompressionType.Deflate))
2026-01-08 15:34:48 +00:00
{
// Write single file
using (var fileStream = File.OpenRead("source.txt"))
{
writer.Write("entry.txt", fileStream, DateTime.Now);
}
// Write directory
writer.WriteAll("C:\\source", "*", SearchOption.AllDirectories);
writer.WriteAll("C:\\source", "*.txt", SearchOption.TopDirectoryOnly);
// Async variants
using (var fileStream = File.OpenRead("source.txt"))
{
await writer.WriteAsync("entry.txt", fileStream, DateTime.Now, cancellationToken);
}
await writer.WriteAllAsync("C:\\source", "*", SearchOption.AllDirectories, cancellationToken);
}
```
---
## Common Options
### ReaderOptions
```csharp
var options = new ReaderOptions
{
Password = "password", // For encrypted archives
LeaveStreamOpen = true, // Don't close wrapped stream
ArchiveEncoding = new ArchiveEncoding // Custom character encoding
{
Default = Encoding.GetEncoding(932)
}
};
2026-01-15 13:29:57 +00:00
using (var archive = ZipArchive.OpenArchive("file.zip", options))
2026-01-08 15:34:48 +00:00
{
// ...
}
```
### WriterOptions
```csharp
var options = new WriterOptions(CompressionType.Deflate)
{
CompressionLevel = 9, // 0-9 for Deflate
LeaveStreamOpen = true, // Don't close stream
};
archive.SaveTo("output.zip", options);
```
### ExtractionOptions
```csharp
var options = new ExtractionOptions
{
ExtractFullPath = true, // Recreate directory structure
Overwrite = true, // Overwrite existing files
PreserveFileTime = true // Keep original timestamps
};
archive.WriteToDirectory(@"C:\output", options);
```
---
## Compression Types
### Available Compressions
```csharp
// For creating archives
CompressionType.None // No compression (store)
CompressionType.Deflate // DEFLATE (default for ZIP/GZip)
2026-01-12 16:08:16 +00:00
CompressionType.Deflate64 // Deflate64
2026-01-08 15:34:48 +00:00
CompressionType.BZip2 // BZip2
CompressionType.LZMA // LZMA (for 7Zip, LZip, XZ)
CompressionType.PPMd // PPMd (for ZIP)
CompressionType.Rar // RAR compression (read-only)
2026-01-12 16:08:16 +00:00
CompressionType.ZStandard // ZStandard
ArchiveType.Arc
ArchiveType.Arj
ArchiveType.Ace
// For Tar archives with compression
// Use WriterFactory to create compressed tar archives
2026-01-15 13:29:57 +00:00
using (var writer = WriterFactory.OpenWriter(stream, ArchiveType.Tar, CompressionType.GZip)) // Tar.GZip
using (var writer = WriterFactory.OpenWriter(stream, ArchiveType.Tar, CompressionType.BZip2)) // Tar.BZip2
2026-01-08 15:34:48 +00:00
```
### Archive Types
```csharp
ArchiveType.Zip
ArchiveType.Tar
ArchiveType.GZip
ArchiveType.BZip2
ArchiveType.Rar
ArchiveType.SevenZip
ArchiveType.XZ
ArchiveType.ZStandard
```
---
## Patterns & Examples
### Extract with Error Handling
```csharp
try
{
using (var archive = ZipArchive.Open("archive.zip",
new ReaderOptions { Password = "password" }))
{
archive.WriteToDirectory(@"C:\output", new ExtractionOptions
{
ExtractFullPath = true,
Overwrite = true
});
}
}
catch (PasswordRequiredException)
{
Console.WriteLine("Password required");
}
catch (InvalidArchiveException)
{
Console.WriteLine("Archive is invalid");
}
catch (SharpCompressException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
### Extract with Progress
```csharp
var progress = new Progress<ProgressReport>(report =>
{
Console.WriteLine($"Extracting {report.EntryPath}: {report.PercentComplete}%");
});
var options = new ReaderOptions { Progress = progress };
2026-01-15 13:29:57 +00:00
using (var archive = ZipArchive.OpenArchive("archive.zip", options))
2026-01-08 15:34:48 +00:00
{
archive.WriteToDirectory(@"C:\output");
}
```
### Async Extract with Cancellation
```csharp
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromMinutes(5));
try
{
2026-01-15 13:04:09 +00:00
using (var archive = await ZipArchive.OpenAsyncArchive("archive.zip"))
2026-01-08 15:34:48 +00:00
{
2026-01-12 16:08:16 +00:00
await archive.WriteToDirectoryAsync(
@"C:\output",
2026-01-08 15:34:48 +00:00
new ExtractionOptions { ExtractFullPath = true, Overwrite = true },
2026-01-12 16:08:16 +00:00
cancellationToken: cts.Token
);
2026-01-08 15:34:48 +00:00
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Extraction cancelled");
}
```
### Create with Custom Compression
```csharp
2026-01-15 13:04:09 +00:00
using (var archive = ZipArchive.CreateArchive())
2026-01-08 15:34:48 +00:00
{
archive.AddAllFromDirectory(@"D:\source");
// Fastest
2026-01-15 13:04:09 +00:00
archive.SaveTo("fast.zip", new WriterOptions(CompressionType.Deflate)
{
CompressionLevel = 1
2026-01-08 15:34:48 +00:00
});
// Balanced (default)
archive.SaveTo("normal.zip", CompressionType.Deflate);
// Best compression
2026-01-15 13:04:09 +00:00
archive.SaveTo("best.zip", new WriterOptions(CompressionType.Deflate)
{
CompressionLevel = 9
2026-01-08 15:34:48 +00:00
});
}
```
### Stream Processing (No File I/O)
```csharp
using (var outputStream = new MemoryStream())
2026-01-15 13:04:09 +00:00
using (var archive = ZipArchive.CreateArchive())
2026-01-08 15:34:48 +00:00
{
// Add content from memory
using (var contentStream = new MemoryStream(Encoding.UTF8.GetBytes("Hello")))
{
archive.AddEntry("file.txt", contentStream);
}
// Save to memory
archive.SaveTo(outputStream, CompressionType.Deflate);
// Get bytes
byte[] archiveBytes = outputStream.ToArray();
}
```
### Extract Specific Files
```csharp
2026-01-15 13:29:57 +00:00
using (var archive = ZipArchive.OpenArchive("archive.zip"))
2026-01-08 15:34:48 +00:00
{
var filesToExtract = new[] { "file1.txt", "file2.txt" };
foreach (var entry in archive.Entries.Where(e => filesToExtract.Contains(e.Key)))
{
entry.WriteToFile(@"C:\output\" + entry.Key);
}
}
```
### List Archive Contents
```csharp
2026-01-15 13:29:57 +00:00
using (var archive = ZipArchive.OpenArchive("archive.zip"))
2026-01-08 15:34:48 +00:00
{
foreach (var entry in archive.Entries)
{
if (entry.IsDirectory)
Console.WriteLine($"[DIR] {entry.Key}");
else
Console.WriteLine($"[FILE] {entry.Key} ({entry.Size} bytes)");
}
}
```
---
## Common Mistakes
### ✗ Wrong - Stream not disposed
```csharp
var stream = File.OpenRead("archive.zip");
2026-01-15 13:29:57 +00:00
var archive = ZipArchive.OpenArchive(stream);
2026-01-08 15:34:48 +00:00
archive.WriteToDirectory(@"C:\output");
// stream not disposed - leaked resource
```
### ✓ Correct - Using blocks
```csharp
using (var stream = File.OpenRead("archive.zip"))
2026-01-15 13:29:57 +00:00
using (var archive = ZipArchive.OpenArchive(stream))
2026-01-08 15:34:48 +00:00
{
archive.WriteToDirectory(@"C:\output");
}
// Both properly disposed
```
### ✗ Wrong - Mixing API styles
```csharp
// Loading entire archive then iterating
2026-01-15 13:29:57 +00:00
using (var archive = ZipArchive.OpenArchive("large.zip"))
2026-01-08 15:34:48 +00:00
{
var entries = archive.Entries.ToList(); // Loads all in memory
foreach (var e in entries)
{
e.WriteToFile(...); // Then extracts each
}
}
```
### ✓ Correct - Use Reader for large files
```csharp
// Streaming iteration
using (var stream = File.OpenRead("large.zip"))
2026-01-15 13:29:57 +00:00
using (var reader = ReaderFactory.OpenReader(stream))
2026-01-08 15:34:48 +00:00
{
while (reader.MoveToNextEntry())
{
reader.WriteEntryToDirectory(@"C:\output");
}
}
```
---
## Related Documentation
- [USAGE.md](USAGE.md) - Complete code examples
- [FORMATS.md](FORMATS.md) - Supported formats
- [PERFORMANCE.md](PERFORMANCE.md) - API selection guide