C#:只提取一个压缩文件(没有文件夹) [英] C#: Extract a zipped file only (without the folder)

查看:320
本文介绍了C#:只提取一个压缩文件(没有文件夹)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着SharpZip lib中,我可以很容易地提取从ZIP档案文件:

With the SharpZip lib I can easily extract a file from a zip archive:

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



然而,这会将未压缩的文件夹中的输出目录。
假设有内bla.zip我想foo​​.txt的文件。有一个简单的方法,只是提取,并将其放置在输出目录(不带文件夹)?

However this puts the uncompressed folder in the output directory. Suppose there is a foo.txt file within bla.zip which I want. Is there an easy way to just extract that and place it in the output directory (without the folder)?

推荐答案

FastZip 似乎并没有提供一种方法来改变文件夹,但的操作支持此的手动方式。

The FastZip does not seem to provide a way to change folders, but the "manual" way of doing supports this.

如果你看看他们的例子:

If you take a look at their example:

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



由于他们注意,而不是写作:

As they note, instead of writing:

String entryFileName = zipEntry.Name;



你可以写:

you can write:

String entryFileName = Path.GetFileName(entryFileName)

要删除的文件夹。

这篇关于C#:只提取一个压缩文件(没有文件夹)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆