SharpLibZip:添加没有路径的文件 [英] SharpLibZip: Add file without path

查看:289
本文介绍了SharpLibZip:添加没有路径的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码,使用 SharpZipLib 库,将文件添加到.zip文件,但每个文件都以其完整路径存储。我需要只存储该文件,在.zip文件的'根'。

I'm using the following code, using the SharpZipLib library, to add files to a .zip file, but each file is being stored with its full path. I need to only store the file, in the 'root' of the .zip file.

string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
     zipFile.BeginUpdate();
     foreach (string file in files)
     {
          zipFile.Add(file);
     }
     zipFile.CommitUpdate();
}



我在提供的文档中找不到有关此选项的任何内容。

I can't find anything about an option for this in the supplied documentation. As this is a very popular library, I hope someone reading this may know something.

推荐答案

我的解决方案是设置 NameTransform ZipFile 的物件属性至 ZipNameTransform c $ c> TrimPrefix 设置为文件的目录。这会导致删除条目名称的目录部分,即完整的文件路径。

My solution was to set the NameTransform object property of the ZipFile to a ZipNameTransform with its TrimPrefix set to the directory of the file. This causes the directory part of the entry names, which are full file paths, to be removed.

public static void ZipFolderContents(string folderPath, string zipFilePath)
{
    string[] files = Directory.GetFiles(folderPath);
    using (ZipFile zipFile = ZipFile.Create(zipFilePath))
    {
        zipFile.NameTransform = new ZipNameTransform(folderPath);
        foreach (string file in files)
        {
            zipFile.BeginUpdate();
            zipFile.Add(file);
            zipFile.CommitUpdate();
        }
    }
}

属性的类型为 INameTransform ,允许自定义名称transforms。

What's cool is the the NameTransform property is of type INameTransform, allowing customisation of the name transforms.

这篇关于SharpLibZip:添加没有路径的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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