-3

我有以下在 powershell 中正常工作的内容,想知道如何在 C# 中做同样的事情。我需要找到 .zip 文件,并将它们一个一个解压缩到临时位置搜索内容,如果找到则列出文件,然后删除临时文件继续下一个。

我的问题是;能够完成解压缩、文件搜索和删除功能的相应 C# 方法是什么?

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();
    }
}
4

1 回答 1

1

这是您在 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);
        }
    }
}

您可以使用 GetFiles 方法列出匹配的文件

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

最后,您可以使用File.DeleteDirectory.Delete删除文件和目录。

于 2014-07-21T17:25:51.007 回答