【问题标题】:Zip files without inclusion of folders压缩文件而不包含文件夹
【发布时间】:2018-11-28 01:32:39
【问题描述】:

我正在使用 System.IO.Compression 将文件压缩为 .zip,位于源代码下方:

using (FileStream zipToOpen = new FileStream(zipName, FileMode.CreateNew)){
  using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)){
    ZipArchiveEntry readmeEntry = archive.CreateEntry(@"C:\Users\soc\myFold\someFile.xml");
  }
}

这段代码运行良好,但不幸的是,在 .zip 中有整个文件夹序列(C: -> Users -> ... -> someFile.xml);我可以只获得我需要的文件的最终 .zip 吗?我知道对于其他库,这一事实是可能的 (DotNetZip add files without creating folders),但我想知道标准库是否可以这样做。

【问题讨论】:

    标签: c# zip system.io.compression


    【解决方案1】:

    您似乎认为该文件将被添加到存档中,但事实并非如此。 CreateEntry 只是创建了一个指定路径和入口名称的入口,你还需要编写实际的文件。
    实际上,您问题中的代码与文档中的代码非常相似,所以我假设您是从那里得到的?

    无论如何,要仅获取文件名,您可以使用Path.GetFileName,然后您可以将实际文件内容写入 zip 条目。

    var filePath = @"C:\temp\foo.txt";
    var zipName = @"C:\temp\foo.zip";
    
    using (FileStream zipToOpen = new FileStream(zipName, FileMode.CreateNew))
    {
        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
        {
            ZipArchiveEntry readmeEntry = archive.CreateEntry(Path.GetFileName(filePath));
            using (StreamReader reader = new StreamReader(filePath))
            using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
            {
                writer.Write(reader.ReadToEnd());
            }
        }
    }
    

    上面的代码将在根目录中创建一个带有foo.txt 和源文件内容的存档,而不需要任何其他目录。

    【讨论】:

    • 非常感谢@Stijn!你是对的,因为这是我第一次需要这个库,所以我复制了这个例子……它工作得很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多