如何用C#或PowerShell递归列出归档文件内所有文件(无需解压)
当然可以!不管是PowerShell还是C#都能轻松实现这个需求——无需解压就能递归列出归档文件里的所有内容,包括嵌套在子归档里的文件。下面分别给出两种方案:
PowerShell 实现
PowerShell可以直接调用.NET的System.IO.Compression.ZipArchive类来实现递归遍历。这里写一个自定义函数,会自动处理所有嵌套的zip文件:
function Get-ZipContents { param( [Parameter(Mandatory=$true)] [string]$ZipPath ) # 先输出当前归档文件本身 Write-Output $ZipPath # 打开zip归档流 $zipStream = [System.IO.File]::OpenRead($ZipPath) try { $zipArchive = [System.IO.Compression.ZipArchive]::new($zipStream, [System.IO.Compression.ZipArchiveMode]::Read) foreach ($entry in $zipArchive.Entries) { # 输出当前条目(文件或文件夹) Write-Output "$ZipPath\$($entry.FullName)" # 如果当前条目是zip文件,递归处理子归档 if ($entry.Name.EndsWith('.zip', [System.StringComparison]::OrdinalIgnoreCase)) { # 创建临时文件暂存子zip内容 $tempPath = [System.IO.Path]::GetTempFileName() try { $entry.Open().CopyTo([System.IO.File]::OpenWrite($tempPath)) Get-ZipContents -ZipPath $tempPath } finally { # 用完自动删除临时文件 Remove-Item $tempPath -Force -ErrorAction SilentlyContinue } } } } finally { $zipStream.Close() } } # 调用函数,替换为你的test.zip实际路径 Get-ZipContents -ZipPath "C:\your\path\test.zip"
说明
- 函数会先输出当前zip文件路径,再遍历其中所有条目(文件/文件夹)
- 遇到后缀为
.zip的文件时,会临时提取到本地(用完自动清理),然后递归遍历这个子归档的内容 - 输出格式类似:
test.zip,test.zip\1.txt,test.zip\subarchive.zip,test.zip\subarchive.zip\3.txt,你可以根据需求调整输出的字符串格式
C# 实现
如果需要更严谨的程序级实现,C#是更好的选择。同样利用System.IO.Compression命名空间的类来完成递归遍历:
首先创建一个控制台应用,然后添加以下代码:
using System; using System.IO; using System.IO.Compression; class Program { static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("请传入zip文件路径作为命令行参数"); return; } string zipPath = args[0]; ListZipContents(zipPath); } static void ListZipContents(string zipPath) { // 输出当前归档文件 Console.WriteLine(zipPath); using (var zipStream = File.OpenRead(zipPath)) using (var zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Read)) { foreach (var entry in zipArchive.Entries) { // 输出当前条目的完整路径 string fullEntryPath = Path.Combine(zipPath, entry.FullName); Console.WriteLine(fullEntryPath); // 判断是否为嵌套的zip文件 if (entry.Name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) { // 创建临时文件保存子zip内容 string tempPath = Path.GetTempFileName(); try { using (var entryStream = entry.Open()) using (var tempStream = File.OpenWrite(tempPath)) { entryStream.CopyTo(tempStream); } // 递归遍历子归档 ListZipContents(tempPath); } finally { // 清理临时文件 if (File.Exists(tempPath)) { File.Delete(tempPath); } } } } } } }
说明
- 程序接收一个命令行参数(zip文件路径),然后递归遍历所有层级的内容
- 同样会处理嵌套的zip文件,临时提取后递归遍历,最后自动清理临时文件
- 输出的路径会清晰展示层级关系,比如
test.zip\subarchive.zip\3.txt,你可以修改Console.WriteLine的内容来调整成你想要的扁平格式
两种方案都能满足你的需求:如果只是快速查询文件结构,PowerShell更轻便;如果需要集成到项目中,C#的实现更可控、可扩展。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

