简体   繁体   English

如何使用SharpZipLib库仅压缩不带文件夹的文件? (C#)

[英]How to compress only files without folders using the SharpZipLib library? (C#)

I use the following code to create a zip file: 我使用以下代码创建一个zip文件:

var files = Directory.GetFiles(targetPath);
var zip = ZipFile.Create(targetPath + "/myzip.zip");
zip.BeginUpdate();
foreach (var file in files) zip.Add(file, CompressionMethod.Deflated);
zip.CommitUpdate();
zip.Close();

I get the following structure of archive: 我得到档案的以下结构:

myzip.zip
   - Folder1
      - Folder2
        - File1.txt
        - File2.txt
        - File3.txt

But I need: 但是我需要:

myzip.zip
  - File1.txt
  - File2.txt
  - File3.txt

Help please. 请帮助。

Looking at the SharpZipLib code, there's this method in the ZipFile class which would seem to do what you want: 查看SharpZipLib代码,ZipFile类中有此方法,该方法似乎可以满足您的要求:

public void Add(IStaticDataSource dataSource, string entryName, CompressionMethod compressionMethod)

You just have to get an IStaticDataSource from the file, and create the appropriate entryName (that doesn't include the directory path), ie search for the last directory separator Path.DirectorySeparatorChar Field in file string and anything after that should be just your filename. 您只需要从文件中获取IStaticDataSource,然后创建适当的entryName(不包含目录路径),即搜索file字符串中的最后一个目录分隔符Path.DirectorySeparatorChar字段 ,之后的所有内容都应该是您的文件名。

[EDIT] Clarification: I had originally suggested Add(string file, string entryName) but edited to the above method when I saw that the OP was specifying a compressionMethod in the call. [编辑]澄清:我最初建议使用Add(string file, string entryName)但是当我看到OP在调用中指定了compressionMethod时,将其编辑为上述方法。 But the default compressionMethod for new zip entries is CompressionMethod.Deflated, so using the Add(string file, string entryName) method should give the same result w/o having to get an IStaticDataSource. 但是新zip条目的默认CompressionMethod是CompressionMethod.Deflated,因此使用Add(string file, string entryName)方法应该获得与不必获取IStaticDataSource相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM