我有以下在 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();
}
}