Search code examples
c#powershellunzipfile-search

Powershell .NET System.IO.Compression to C# .NET Conversion


I have the following which works correctly in powershell was wondering how to do the same thing in C#. I need to find the .zip files and one by one unzip them to a temporary location search through the contents, list file if found then remove temp file move on to the next.

My question is; What would be the corresponding C# methods to be able to accomplish the unzip, file search and delete functionalities?

function Lookin-Zips() {
    param ($SearchPattern);
    $archive = [System.IO.Compression.ZipFile]::OpenRead($archivePath);
    try {
        # enumerate all entries in the archive, which includes both files and directories
        foreach($archiveEntry in $archive.Entries) {
            # if the entry is not a directory (which ends with /)
            if($archiveEntry.FullName -notmatch '/$') {
                # get temporary file -- note that this will also create the file
                $tempFile = [System.IO.Path]::GetTempFileName();
                try {
                    # extract to file system
                    [System.IO.Compression.ZipFileExtensions]::ExtractToFile($archiveEntry, $tempFile, $true);

                    # create PowerShell backslash-friendly path from ZIP path with forward slashes
                    $windowsStyleArchiveEntryName = $archiveEntry.FullName.Replace('/', '\');
                    # run selection
                    Get-ChildItem $tempFile | Select-String -pattern "$SearchPattern" | Select-Object @{Name="Filename";Expression={$windowsStyleArchiveEntryName}}, @{Name="Path";Expression={Join-Path $archivePath (Split-Path $windowsStyleArchiveEntryName -Parent)}}, Matches, LineNumber
                }
                finally {
                    Remove-Item $tempFile;
                }
            }
        }
    }

    finally {
        # release archive object to prevent leaking resources
        $archive.Dispose();
    }
}

Solution

  • This is how you unzip your files in c#

    using System;
    using System.IO;
    using System.IO.Compression;
    
    namespace ConsoleApplication
    {
        class Program
        {
            static void Main(string[] args)
            {
                string startPath = @"c:\example\start";
                string zipPath = @"c:\example\result.zip";
                string extractPath = @"c:\example\extract";
    
                ZipFile.CreateFromDirectory(startPath, zipPath);
    
                ZipFile.ExtractToDirectory(zipPath, extractPath);
            }
        }
    }
    

    And you can use GetFiles method to list the matching file

    public static string[] GetFiles(
        string path,
        string searchPattern
    )
    

    And last you can use File.Delete and Directory.Delete to delete files and directories.