Skip to content

GridLab File Zipper - Skills Guide

Skill Type: File Management
Technology Stack: .NET, ABP Framework, File Compression
Complexity Level: Beginner
Last Updated: 2024


📋 Overview

The GridLab File Zipper module provides robust file compression capabilities for ABP Framework applications with support for modularity, localization, and enterprise-grade file management.

Key Capabilities

  • ✅ Multi-file compression to ZIP archives
  • ✅ Factory pattern for flexible zipper creation
  • ✅ Stream-based operations for memory efficiency
  • ✅ Integration with ABP Framework
  • ✅ Modular and maintainable architecture
  • ✅ Support for large file operations

Prerequisites

  • .NET 9.0 or higher
  • NuGet package manager
  • File system access permissions

🚀 Quick Start

Step 1: Install NuGet Package

Install the GridLab.Abp.FileZipper package from NuGet:

Install-Package GridLab.Abp.FileZipper

Package Information:

Step 2: Add Module Dependency

Add the AbpGridLabFileZipperModule to your ABP module's dependency list:

[DependsOn(
    //...other dependencies
    typeof(AbpGridLabFileZipperModule)
)]
public class YourModule : AbpModule
{
}

💡 Usage Examples

Basic File Compression

public class DocumentArchiveService : ITransientDependency
{
    private readonly IFileZipperFactory _fileZipperFactory;
    private readonly ILogger<DocumentArchiveService> _logger;

    public DocumentArchiveService(
        IFileZipperFactory fileZipperFactory,
        ILogger<DocumentArchiveService> logger)
    {
        _fileZipperFactory = fileZipperFactory;
        _logger = logger;
    }

    public void CreateArchive(IEnumerable<string> filePaths, string outputZipPath)
    {
        try
        {
            var fileZipper = _fileZipperFactory.Create();
            fileZipper.ZipFiles(filePaths, outputZipPath);

            _logger.LogInformation(
                "Successfully created archive at {ArchivePath} with {FileCount} files",
                outputZipPath,
                filePaths.Count()
            );
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create archive at {ArchivePath}", outputZipPath);
            throw;
        }
    }
}

Batch Document Compression

public class ReportArchiveService : ITransientDependency
{
    private readonly IFileZipperFactory _fileZipperFactory;
    private readonly IWebHostEnvironment _environment;

    public ReportArchiveService(
        IFileZipperFactory fileZipperFactory,
        IWebHostEnvironment environment)
    {
        _fileZipperFactory = fileZipperFactory;
        _environment = environment;
    }

    public async Task<string> ArchiveMonthlyReportsAsync(int year, int month)
    {
        var reportDirectory = Path.Combine(
            _environment.ContentRootPath,
            "Reports",
            year.ToString(),
            month.ToString("D2")
        );

        var reportFiles = Directory.GetFiles(reportDirectory, "*.pdf");

        var archivePath = Path.Combine(
            reportDirectory,
            $"Reports_{year}_{month:D2}.zip"
        );

        var fileZipper = _fileZipperFactory.Create();
        fileZipper.ZipFiles(reportFiles, archivePath);

        return archivePath;
    }
}

Temporary File Cleanup with Compression

public class TemporaryFileService : ITransientDependency
{
    private readonly IFileZipperFactory _fileZipperFactory;

    public TemporaryFileService(IFileZipperFactory fileZipperFactory)
    {
        _fileZipperFactory = fileZipperFactory;
    }

    public void ArchiveAndCleanupTempFiles(string tempDirectory)
    {
        var tempFiles = Directory.GetFiles(tempDirectory);

        if (tempFiles.Any())
        {
            var archivePath = Path.Combine(
                tempDirectory,
                $"archive_{DateTime.Now:yyyyMMdd_HHmmss}.zip"
            );

            // Create archive
            var fileZipper = _fileZipperFactory.Create();
            fileZipper.ZipFiles(tempFiles, archivePath);

            // Delete original files after successful archiving
            foreach (var file in tempFiles)
            {
                File.Delete(file);
            }
        }
    }
}

User Export Service

public class UserDataExportService : ITransientDependency
{
    private readonly IFileZipperFactory _fileZipperFactory;
    private readonly IRepository<User, Guid> _userRepository;

    public UserDataExportService(
        IFileZipperFactory fileZipperFactory,
        IRepository<User, Guid> userRepository)
    {
        _fileZipperFactory = fileZipperFactory;
        _userRepository = userRepository;
    }

    public async Task<byte[]> ExportUserDataAsZipAsync(Guid userId)
    {
        var user = await _userRepository.GetAsync(userId);

        var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
        Directory.CreateDirectory(tempPath);

        try
        {
            // Generate user data files
            var profilePath = Path.Combine(tempPath, "profile.json");
            var activityPath = Path.Combine(tempPath, "activity.csv");

            await File.WriteAllTextAsync(profilePath, JsonSerializer.Serialize(user));
            // ... write activity data

            var filesToZip = new[] { profilePath, activityPath };
            var zipPath = Path.Combine(tempPath, "user_data.zip");

            var fileZipper = _fileZipperFactory.Create();
            fileZipper.ZipFiles(filesToZip, zipPath);

            return await File.ReadAllBytesAsync(zipPath);
        }
        finally
        {
            // Cleanup temp directory
            Directory.Delete(tempPath, true);
        }
    }
}

🔧 Advanced Scenarios

Integration with File Management System

public class FileManagementService : ITransientDependency
{
    private readonly IFileZipperFactory _fileZipperFactory;
    private readonly IBlobContainer _blobContainer;

    public FileManagementService(
        IFileZipperFactory fileZipperFactory,
        IBlobContainer blobContainer)
    {
        _fileZipperFactory = fileZipperFactory;
        _blobContainer = blobContainer;
    }

    public async Task<string> ArchiveAndUploadAsync(
        IEnumerable<string> localFilePaths,
        string blobName)
    {
        var tempZipPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.zip");

        try
        {
            // Create ZIP archive
            var fileZipper = _fileZipperFactory.Create();
            fileZipper.ZipFiles(localFilePaths, tempZipPath);

            // Upload to blob storage
            using var fileStream = File.OpenRead(tempZipPath);
            await _blobContainer.SaveAsync(blobName, fileStream);

            return blobName;
        }
        finally
        {
            if (File.Exists(tempZipPath))
            {
                File.Delete(tempZipPath);
            }
        }
    }
}

📚 Best Practices

✅ Do's

  • Use factory pattern to create zipper instances
  • Implement proper error handling and logging
  • Clean up temporary files after compression
  • Validate file paths before compression
  • Use async operations for large files
  • Implement progress reporting for long operations

❌ Don'ts

  • Don't compress already compressed files (limited benefit)
  • Don't keep large ZIP files in memory
  • Don't forget to dispose of file streams
  • Don't compress sensitive data without encryption
  • Don't ignore file path validation

🔍 Troubleshooting

Common Issues

Issue: Out of memory exception

  • Solution: Process large files in chunks
  • Solution: Use streaming instead of loading entire file in memory

Issue: Access denied errors

  • Solution: Verify file system permissions
  • Solution: Ensure output directory exists and is writable

Issue: Files not found

  • Solution: Validate all file paths before compression
  • Solution: Use absolute paths instead of relative paths

📖 Additional Resources