【发布时间】:2014-11-07 08:08:36
【问题描述】:
有谁知道如何解压缩已压缩的文件夹,以便只返回文件夹中的文件而不是文件夹本身。
目前我正在使用这个:
ZipFile.ExtractToDirectory(<Zipped File Source>, <Unzipped File Destination>)
这适用于已压缩到一个 zip 文件中的文件,但对于已压缩文件夹中的文件,我只想要文件。
【问题讨论】:
有谁知道如何解压缩已压缩的文件夹,以便只返回文件夹中的文件而不是文件夹本身。
目前我正在使用这个:
ZipFile.ExtractToDirectory(<Zipped File Source>, <Unzipped File Destination>)
这适用于已压缩到一个 zip 文件中的文件,但对于已压缩文件夹中的文件,我只想要文件。
【问题讨论】:
相同的代码解压缩所有文件。
从这里开始:
http://msdn.microsoft.com/en-us/library/hh485723%28v=vs.110%29.aspx
我们有:
将指定 zip 存档中的所有文件解压缩到一个目录 文件系统。
【讨论】:
ZipArchive 对象中遍历所有文件(并将它们保存在任何您喜欢的地方)。这里有一个例子:msdn.microsoft.com/en-us/library/…
感谢Stewart_R,为我指明了正确的方向。
重申一下,下面的“第一种方法”有效,但不是我需要的方式。
第一种方法 (VB):
ZipFile.ExtractToDirectory(<Zipped File Source>, <Unzipped File Destination>)
正如我之前在我的问题中提到的,使用上面的代码解压缩已压缩在一起的文件或包含文件的文件夹,但执行后者将导致文件夹名称与里面的文件。为了只得到文件,试试这个第二种方法(VB):
Using archive As ZipArchive = ZipFile.OpenRead(<zip_file_path>) // "<zip_file_path>" is the location of your zip file
For Each entry As ZipArchiveEntry In archive.Entries
If entry.Name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) Then // ".txt" is the extention that you're looking for
entry.ExtractToFile(Path.Combine(<unzip_to_path>, entry.Name)) // "<unzip_to_path>" is the destination folder
End If
Next
End Using
注意:
"entry.Name" 返回带有扩展名的实际文件名,即;
"somefile.txt"
这很重要,因为使用“第一种方法”解压缩会返回;
"folder_name/somefile.txt"
如果您替换,则可以使用“第二种方法”复制此行为;
"entry.Name"
与;
"entry.FullName"
最后说明:
如果您尝试匹配多个扩展名,您可以添加“或”(VB) 或 || (C#) 条件内:
VB:
entry.Name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) or
entry.Name.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) Then
C#:
entry.Name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) ||
entry.Name.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) Then
【讨论】: