简体   繁体   English

使用.NET ZipArchive压缩整个目录以及其他信息

[英]Using .NET ZipArchive to zip entire directories AS well as extra info

I inherited some code that makes use of ZipArchive to save some information from the database. 我继承了一些代码,这些代码利用ZipArchive从数据库中保存了一些信息。 It uses BinaryFormatter to do this. 它使用BinaryFormatter来做到这一点。 When you look at the zip file with 7-zip (for example), you see a couple of folders and a .txt file. 当您查看带有7-zip的zip文件(例如)时,会看到几个文件夹和一个.txt文件。 All is working well. 一切都很好。 I simply want to modify the code to also have a folder in the ZipArchive called "temp" that consists of files and folders under C:\\temp. 我只是想修改代码,使其在ZipArchive中也有一个名为“ temp”的文件夹,该文件夹由C:\\ temp下的文件和文件夹组成。 Is there an easy way to add a entry (ZipArchiveEntry?) that consist of an entire folder or the disc? 有没有简单的方法来添加包含整个文件夹或光盘的条目(ZipArchiveEntry?)? I saw "CreateEntryFromFile" in the member methods of ZipArchive, but no CreateEntryFromDirectory. 我在ZipArchive的成员方法中看到“ CreateEntryFromFile”,但没有CreateEntryFromDirectory。 Or perhaps there's some other simple way to do it? 也许还有其他简单的方法可以做到这一点? Anyone have example code? 有人有示例代码吗? I should say that C:\\temp could have variable number of files and directories (that have child directories and files, etc.) Must I enumerate them somehow, create my own directories use CreateEntryFromFile? 我应该说C:\\ temp可能具有可变数量的文件和目录(具有子目录和文件等)。我是否必须以某种方式枚举它们,使用CreateEntryFromFile创建自己的目录? Any help is appreciated. 任何帮助表示赞赏。

Similarly, when I read the ZipArchive, I want to take the stuff related to C:\\temp and just dump it in a directory (like C:\\temp_old) Thanks, Dave 同样,当我阅读ZipArchive时,我想将与C:\\ temp相关的内容放到一个目录中(例如C:\\ temp_old),谢谢。

The answer by user1469065 in Zip folder in C# worked for me. C14中Zip文件夹中 user1469065的答案为我工作。 user1469065 shows how to get all the files/directories in the directory (using some cool "yield" statements) and then do the serialization. user1469065显示如何获取目录中的所有文件/目录(使用一些很酷的“ yield”语句),然后进行序列化。 For completeness, I did add the code to deserialize as user1469065 suggested (at least I think I did it the way he suggested). 为了完整起见,我确实按照user1469065的建议添加了要反序列化的代码(至少我认为我是按照他的建议进行的)。

private static void ReadTempFileStuff(ZipArchive archive) // adw
    {
        var sessionArchives = archive.Entries.Where(x => x.FullName.StartsWith(@"temp_directory_contents")).ToArray();
        if (sessionArchives != null && sessionArchives.Length > 0)
        {
            foreach (ZipArchiveEntry entry in sessionArchives)
            {
                FileInfo info = new FileInfo(@"C:\" + entry.FullName);
                if (!info.Directory.Exists)
                {
                    Directory.CreateDirectory(info.DirectoryName);
                }
                entry.ExtractToFile(@"C:\" + entry.FullName,true);
            }
        }
    }

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

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