C#:仅提取压缩文件(不带文件夹)

使用SharpZip lib,我可以轻松地从zip存档中提取文件:

FastZip fz = new FastZip(); string path = "C:/bla.zip"; fz.ExtractZip(bla,"C:/Unzips/",".*"); 

但是,这会将未压缩的文件夹放在输出目录中。 假设bla.zip中有一个我想要的foo.txt文件。 有没有一种简单的方法来提取它并将其放在输出目录(没有文件夹)?

FastZip似乎没有提供更改文件夹的方法,但“手动”方式支持这一点 。

如果你看看他们的例子:

 public void ExtractZipFile(string archiveFilenameIn, string outFolder) { ZipFile zf = null; try { FileStream fs = File.OpenRead(archiveFilenameIn); zf = new ZipFile(fs); foreach (ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) continue; // Ignore directories String entryFileName = zipEntry.Name; // to remove the folder from the entry: // entryFileName = Path.GetFileName(entryFileName); byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zf.GetInputStream(zipEntry); // Manipulate the output filename here as desired. String fullZipToPath = Path.Combine(outFolder, entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) Directory.CreateDirectory(directoryName); using (FileStream streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } finally { if (zf != null) { zf.IsStreamOwner = true;stream zf.Close(); } } } 

正如他们所指出的,而不是写作:

 String entryFileName = zipEntry.Name; 

你可以写:

 String entryFileName = Path.GetFileName(entryFileName) 

删除文件夹。

假设您知道这是zip中唯一的文件(不是文件夹):

 using(ZipFile zip = new ZipFile(zipStm)) { foreach(ZipEntry ze in zip) if(ze.IsFile)//must be our foo.txt { using(var fs = new FileStream(@"C:/Unzips/foo.txt", FileMode.OpenOrCreate, FileAccess.Write)) zip.GetInputStream(ze).CopyTo(fs); break; } } 

如果您需要处理其他可能性,或者例如获取zip-entry的名称,则复杂性会相应增加。